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
You can do this with a case
expression:
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;
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 |
+----+---+---------+
Use 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
Sample result in SQL Fiddle