【发布时间】:2021-06-29 08:41:13
【问题描述】:
我有以下数据
drop table if exists states;
create table states (id integer, state varchar(100), content varchar(100));
insert into states (id, state, content) values (1, 'soc', '73');
insert into states (id, state, content) values (2, 'range', '412');
insert into states (id, state, content) values (3, 'range', '410');
insert into states (id, state, content) values (3, 'soc', '71');
insert into states (id, state, content) values (5, 'range', '405');
使用以下语句
SELECT id,
CASE WHEN state = 'range' THEN content ELSE null END AS 'range',
CASE WHEN state = 'soc' THEN content ELSE null END AS 'soc'
FROM states;
结果是
| id | range | soc |
|---|---|---|
| 1 | 73 | |
| 2 | 412 | |
| 3 | 410 | |
| 3 | 71 | |
| 5 | 405 |
但我希望将 id 为 3 的两行合并为一行
| id | range | soc |
|---|---|---|
| 1 | 73 | |
| 2 | 412 | |
| 3 | 410 | 71 |
| 5 | 405 |
必须改变什么才能达到想要的结果?
【问题讨论】:
-
GROUP BY id和MAX(CASE ..)(或MIN())。 -
感谢您的指点,但我能否请您给出更详细的答案,应该如何应用这些陈述?