Mysql 行中的 table 行移动并合并到命名列中
Mysql rows from one table moved and merged into named columns
我有以下数据
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
范围
社会
1
73
2
412
3
410
3
71
5
405
但我想将id为3的两行合并为一行
id
范围
社会
1
73
2
412
3
410
71
5
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
null
73
2
412
null
3
410
null
3
null
71
5
405
null
SELECT id,
MAX(CASE WHEN state = 'range' THEN content END) AS 'range',
MAX(CASE WHEN state = 'soc' THEN content END) AS 'soc'
FROM states
GROUP BY id;
id
range
soc
1
null
73
2
412
null
3
410
71
5
405
null
db<>fiddle here
我有以下数据
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 | 范围 | 社会 |
---|---|---|
1 | 73 | |
2 | 412 | |
3 | 410 | |
3 | 71 | |
5 | 405 |
但我想将id为3的两行合并为一行
id | 范围 | 社会 |
---|---|---|
1 | 73 | |
2 | 412 | |
3 | 410 | 71 |
5 | 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 null 73 2 412 null 3 410 null 3 null 71 5 405 null
SELECT id, MAX(CASE WHEN state = 'range' THEN content END) AS 'range', MAX(CASE WHEN state = 'soc' THEN content END) AS 'soc' FROM states GROUP BY id;
id range soc 1 null 73 2 412 null 3 410 71 5 405 null
db<>fiddle here