[英]SQL count same response in multiple rows
我正在使用由data.world创建的SQL版本,这似乎很通用(可能是MySql的版本)
我的数据如下所示:
ID |SSM | Abortion | Climate |
1 High Low Medium
2 High High Lo
3 Low High High
4 Medium Low Low
我想生成一条输出每列计数的SQL语句,希望它看起来像下面的样子:
Priority | SSM | Abortion | Climate |
High 2 2 1
Medium 1 0 1
Low 1 1 2
在任何数据库中工作的相对简单的方法是使用union all
:
select 'High' as priority,
sum(case when SSM = 'High' then 1 else 0 end) as SSM,
sum(case when Abortion = 'High' then 1 else 0 end) as Abortion,
sum(case when Climate = 'High' then 1 else 0 end) as climate
from t
union all
select 'Medium' as priority,
sum(case when SSM = 'Medium' then 1 else 0 end) as SSM,
sum(case when Abortion = 'Medium' then 1 else 0 end) as Abortion,
sum(case when Climate = 'Medium' then 1 else 0 end) as climate
from t
union all
select 'Low' as priority,
sum(case when SSM = 'Low' then 1 else 0 end) as SSM,
sum(case when Abortion = 'Low' then 1 else 0 end) as Abortion,
sum(case when Climate = 'Low' then 1 else 0 end) as climate
from t;
在大多数数据库中,您可以将其组合为:
select p.priority,
sum(case when t.SSM = p.priority then 1 else 0 end) as SSM,
sum(case when t.Abortion = p.priority then 1 else 0 end) as Abortion,
sum(case when t.Climate = p.priority then 1 else 0 end) as climate
from (select 'High' as priority, 1 as ord union all
select 'Medium' as priority, 2 as ord union all
select 'Low' as priority, 3 as ord
) p cross join
t
group by p.priority, p.ord
order by p.ord;
我接受@Gordon Linoffs的答案,因为这是问题的答案。 但是草莓让我想到我把问题概念化了。 我需要做的是将一个宽数据集转换成一个长数据集,然后进行计数。 我是从使用PIVOT将数据从宽到高翻转的
以我的示例为例:
SELECT t.condition, t.prioirty, count(t.priority)
FROM(
SELECT "Abortion" as condition, df.abortion
FROM df
WHERE df.abortion!=""
UNION ALL
SELECT "SSM" as condition, df.SSM
FROM df
WHERE df.SSM!=""
UNION ALL
SELECT "Climate" as condition, df.climate
FROM df
WHERE df.climate!="" ) as t
GROUP BY t.condition, t.priority
也许有一种更简单的方法可以做到这一点,但是data.world不支持CROSS APPLY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.