我将通过例子解释: 假设我有这样的数据集:
city | n_id n_Y n_O n_M n_F
---------------------------------------
London | 3 1 2 2 1
Milan | 1 1 0 0 1
我希望每个城市都有一排,一个用于伦敦,一个用于米兰。
在每一行中,我需要为每个行添加一列:
最终结果应该是这样的:
SELECT city, COUNT(id) FROM tablename GROUP BY city
任何帮助都会很棒。
编辑:到目前为止我有
{{1}}
答案 0 :(得分:1)
使用条件聚合:
select city, count(*) as n_id,
sum(case when age = 'Y' then 1 else 0 end) as n_Y,
sum(case when age = 'O' then 1 else 0 end) as n_O,
sum(case when gender = 'M' then 1 else 0 end) as n_M,
sum(case when gender = 'F' then 1 else 0 end) as n_F
from t
group by city;