Get column name instead of column value

后端 未结 3 1226
别跟我提以往
别跟我提以往 2021-01-24 05:19

My table table1 is like below

id   d1   d2   d3   d4
1    6    7    8    9
2    13   10   11   12
3    16   17   14   15
4    19   20   21   18
         


        
3条回答
  •  野性不改
    2021-01-24 05:46

    In an RDBMS, it would be more usual to store data something like this:

    DROP TABLE IF EXISTS my_table;
    
    CREATE TABLE my_table
    (id INT NOT NULL
    ,d INT NOT NULL
    ,reading INT NOT NULL
    ,PRIMARY KEY(id,d)
    );
    
    INSERT INTO my_table VALUES
    (1, 1 ,      6),
    (1, 2 ,      7),
    (1, 3 ,      8),
    (1, 4 ,      9),
    (2, 1 ,     13),
    (2, 2 ,     10),
    (2, 3 ,     11),
    (2, 4 ,     12),
    (3, 1 ,     16),
    (3, 2 ,     17),
    (3, 3 ,     14),
    (3, 4 ,     15),
    (4, 1 ,     19),
    (4, 2 ,     20),
    (4, 3 ,     21),
    (4, 4 ,     18);
    
    SELECT * FROM my_table;
    +----+---+---------+
    | id | d | reading |
    +----+---+---------+
    |  1 | 1 |       6 |
    |  1 | 2 |       7 |
    |  1 | 3 |       8 |
    |  1 | 4 |       9 |
    |  2 | 1 |      13 |
    |  2 | 2 |      10 |
    |  2 | 3 |      11 |
    |  2 | 4 |      12 |
    |  3 | 1 |      16 |
    |  3 | 2 |      17 |
    |  3 | 3 |      14 |
    |  3 | 4 |      15 |
    |  4 | 1 |      19 |
    |  4 | 2 |      20 |
    |  4 | 3 |      21 |
    |  4 | 4 |      18 |
    +----+---+---------+
    

    The query to extract the desired result could then be something like this...

    SELECT a.* 
      FROM my_table a 
      JOIN 
         ( SELECT id,MIN(reading) reading FROM my_table GROUP BY id ) b 
        ON b.id = a.id 
       AND b.reading = a.reading;
    +----+---+---------+
    | id | d | reading |
    +----+---+---------+
    |  1 | 1 |       6 |
    |  2 | 2 |      10 |
    |  3 | 3 |      14 |
    |  4 | 4 |      18 |
    +----+---+---------+
    

提交回复
热议问题