Mysql
 sql >> Database >  >> RDS >> Mysql

Come ottenere un set di risultati come la funzione di ritardo di Oracle

Bene, considera quanto segue...

DROP TABLE IF EXISTS abc;

CREATE TABLE abc
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,ColA CHAR(1) NOT NULL
,ColB CHAR(3) NOT NULL   
,ColC INT NOT NULL
);

INSERT INTO abc (ColA,ColB,ColC) VALUES
('A','xxx',40),
('A','YYY',40),
('A','zzz',40),
('B','ABC',50),
('B','BCA',50),
('C','TTT',60),
('C','FFF',60);

SELECT * FROM abc;
+----+------+------+------+
| id | ColA | ColB | ColC |
+----+------+------+------+
|  1 | A    | xxx  |   40 |
|  2 | A    | YYY  |   40 |
|  3 | A    | zzz  |   40 |
|  4 | B    | ABC  |   50 |
|  5 | B    | BCA  |   50 |
|  6 | C    | TTT  |   60 |
|  7 | C    | FFF  |   60 |
+----+------+------+------+

SELECT id,a,b,c
  FROM (
  SELECT id
     , CASE WHEN ColA = @prev_a 
            THEN @curr_a:= '' 
            ELSE @curr_a := ColA END a
     , @prev_a := ColA

     , CASE WHEN ColB = @prev_b 
        THEN @curr_b:= '' 
            ELSE @curr_b := ColB END b
     , @prev_b := ColB

     , CASE WHEN ColC = @prev_c 
            THEN @curr_c:= '' 
            ELSE @curr_c := ColC END c
     , @prev_c := ColC
  FROM abc
     , (SELECT @curr_a = ''
             , @prev_a = ''
             , @curr_b = ''
     , @prev_b = ''
             , @curr_c = ''
     , @prev_c = ''
             ) vars 
 ORDER 
    BY id
    ) x ORDER BY id;
+----+------+------+------+
| id | a    | b    | c    |
+----+------+------+------+
|  1 | A    | xxx  | 40   |
|  2 |      | YYY  |      |
|  3 |      | zzz  |      |
|  4 | B    | ABC  | 50   |
|  5 |      | BCA  |      |
|  6 | C    | TTT  | 60   |
|  7 |      | FFF  |      |
+----+------+------+------+

Dovrei menzionare che questo presuppone la corrispondenza delle regole di confronto (ad es. SET NAMES utf8;)