我有一张桌子
id, location, status
1, london, 1
2, london, 0
3, boston, 1
4, boston, 1
我希望我的查询生成如下内容: -
location, status_1, status_0
london, 1, 1
boston, 2, 0
到目前为止,我有: -
select count(id) as freq, location from my_table
group by location order by freq desc;
我完全迷失在哪里。
答案 0 :(得分:1)
在发出查询的客户端中,这种转换更好,但如果必须在数据库中执行,那么
select location,
sum(status = 1) AS status_1,
sum(status = 0) AS status_0
from my_table
group by location
它有点hackish,但当status为1时'status = 1'将评估为布尔值true,MySQL将礼貌地转换为整数'1',然后将其汇总。当status为0且status = 0的计算结果为true时也是如此。
答案 1 :(得分:1)
所以你想计算每个城市每个州的记录吗?
在下面的查询中,我按位置分组(就像你的那样),然后为每个状态添加一个总和。总和内部是一种情况,如果记录与期望状态匹配则返回1,否则返回0。这样,您就可以有效地计算每个位置的每个州的记录数。
select
a.location,
sum(case when a.status = 1 then 1 else 0 end) as status_1,
sum(case when a.status = 0 then 1 else 0 end) as status_0
from
YourTable a
group by
a.location
答案 2 :(得分:1)
select location,
sum(case when status = 1 then 1 else 0 end) as status_1,
sum(case when status = 0 then 1 else 0 end) as status_0,
from my_table
group by location;