[英]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.