I have a table pop
with 3 columns: id
,level
,value
:
CREATE TABLE IF NOT EXISTS `pop` (
`id` int(6),
`level` varchar(3),
`value` int(6),
PRIMARY KEY (`id`,`level`)
) DEFAULT CHARSET=utf8;
INSERT INTO `pop` (`id`, `level`, `value`) VALUES
('1', 'MUN', '243'),
('1', 'CAN', '335'),
('1', 'PRO', '345'),
('2', 'DIS', '345'),
('2', 'MUN', '243'),
('3', 'DIS', '335');
There are ~10M ids, and only 4 levels. All id's have at least 1 level. The levels can be "ordered", even if they are strings: ("DIS"<"MUN"<"CAN"<"PRO").
What I would like to achieve is:
- for each id, give me the lowest level possible, and its value.
So the expected output is:
1,'MUN',243
2,'DIS',345
3,'DIS',335
I have tried with
SELECT id,
CASE
when level = 'DIS' THEN level
when level = 'MUN' THEN level
when level = 'CAN' THEN level
when level = 'PRO' THEN level
END as level,
value FROM `pop` order by id, level
But it's not working, it returns the whole table.
Any ideas?
(Btw I am using SQL in AWS Athena)