获取列名而不是列值

时间:2017-10-27 13:11:53

标签: mysql sql

我的表table1如下所示

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

输出表格如

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

我的查询如下:SELECT d1, d2, d3, d4, least(d1, d2, d3, d4) as min FROM table1

我无法编写查询;我如何获得最小值而不是最小值?我将如何完成min_col字段?

3 个答案:

答案 0 :(得分:4)

您可以使用case表达式执行此操作:

SELECT d1, d2, d3, d4, least(d1, d2, d3, d4) as min_value,
       (CASE  least(d1, d2, d3, d4)
            WHEN d1 THEN 'd1'
            WHEN d2 THEN 'd2'
            WHEN d3 THEN 'd3'
            WHEN d4 THEN 'd4'
        END) as min_column_name
FROM table1;

答案 1 :(得分:2)

使用case

SELECT d1, d2, d3, d4, least(d1, d2, d3, d4) as min,
       case when least(d1, d2, d3, d4)=d1 then 'd1'
            when least(d1, d2, d3, d4)=d2 then 'd2'
            when least(d1, d2, d3, d4)=d3 then 'd3'
            when least(d1, d2, d3, d4)=d4 then 'd4' 
           end as min_col
FROM table1

OR

case least(d1, d2, d3, d4)
  when d1 then 'd1'
  when d2 then 'd2'
  when d3 then 'd3'
  when d4 then 'd4' 
end as min_col

SQL Fiddle

中的示例结果

答案 2 :(得分:1)

在RDBMS中,存储类似这样的数据更为常见:

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

提取所需结果的查询可能就是这样......

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