0

我有一张这样的桌子:

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 来解决这个问题。

4

2 回答 2

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

于 2013-03-17T23:11:31.037 回答
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
于 2013-03-17T23:14:28.233 回答