group id gender count
------- ------ -----
01 M 10
01 F 5
02 M 6
03 F 2
选择数据为
groupId Male Female
------- ---- -----
01 10 5
02 6 0
03 0 2
答案 0 :(得分:0)
您必须使用内联视图并加入以执行所需的操作。
您尚未提及表名。我假设为TableName并编写了查询。使用以下内容。
select m.groupId as groupId, m.count as Male,f.count as Female from
(select groupId, gender, count from tablename where gender = 'M')m join (select groupId, gender, count from tablename where gender = 'F')f on m.groupid = f.groupid
答案 1 :(得分:0)
我认为你的表名是test,所以你的查询可能是:
select tab.groupId, sum(CASE WHEN tab.gender = 'M' THEN tab.count ELSE 0 END) as male, sum(CASE WHEN tab.gender = 'F' THEN tab.count ELSE 0 END) as female from test tab group by tab.groupId order by tab.groupId
答案 2 :(得分:0)
一种可能的方式:
with the_table(group_id, gender, count) as(
select 01,'M',10 union all
select 01,'F',5 union all
select 02,'M',6 union all
select 03,'F',2
)
select coalesce(t1.group_id, t2.group_id) as group_id, coalesce(t1.count, 0) as male, coalesce(t2.count, 0) as female
from
(select group_id, count from the_table where gender = 'M') t1
full join
(select group_id, count from the_table where gender = 'F') t2
on t1.group_id = t2.group_id
旁注:count
是列名的不好选择,它是保留关键字