Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Cara mendapatkan hasil yang ditetapkan seperti fungsi lag Oracle

Nah, simak berikut ini...

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

Saya harus menyebutkan bahwa ini mengasumsikan kecocokan susunan (misalnya SET NAMES utf8;)




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. SQL_NO_CACHE untuk Postgresql?

  2. MySQL, kueri terlalu lambat, bagaimana cara memperbaikinya?

  3. cara menghapus baris duplikat dari tabel di mysql

  4. Indeks Hash MySQL untuk Pengoptimalan

  5. Bagaimana saya bisa mengonversi database MySQL ke SQLite di PHP?