用于将值组合转换为列的SQL查询

时间:2013-03-17 23:09:16

标签: sql postgresql crosstab

我有一张这样的表:

user_id, gender, sent
1        M       100
1        F       120
2        M       20
2        F       30

我想要一张上面这样的表格:

user_id, male_sent, female_sent, total_sent 
1        100        120          220 
2        20         30           50 

我缺少(Postgres)SQL foo来解决这个问题。

2 个答案:

答案 0 :(得分:2)

您可以使用带有CASE表达式的聚合函数来获得结果:

select user_id,
  sum(case when gender = 'M' then sent else 0 end) male_sent,
  sum(case when gender = 'F' then sent else 0 end) female_sent,
  sum(sent) total_sent
from yourtable
group by user_id

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

您使用的数据库是什么?

如果您使用的是SQL Server,则可以执行以下操作:

SELECT user_id,sum(case when gender = 'M' then sent else 0 end) as male_sent,
sum(case when gender = 'F' then sent else 0 end) as female_sent,
sum(sent) as total_sent
FROM your_table_name
GROUP BY user_id