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

Sådan får du et resultatsæt som Oracle lag-funktion

Tja, overvej følgende...

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  |      |
+----+------+------+------+

Jeg skal nævne, at dette forudsætter, at sammenstillinger stemmer overens (f.eks. SET NAMES utf8;)




  1. Klon ORACLE_HOME

  2. Migrer fra traditionel replikering til GTID

  3. Hvordan kan jeg se SQL-udførelsesplanen i Oracle?

  4. MySQL-grupper efter intervaller i et datointerval