[英]SQL count same response in multiple rows
I'm working with the SQL version created by data.world which seems pretty generic (probably a version of MySql) 我正在使用由data.world创建的SQL版本,这似乎很通用(可能是MySql的版本)
my data looks like this: 我的数据如下所示:
ID |SSM | Abortion | Climate |
1 High Low Medium
2 High High Lo
3 Low High High
4 Medium Low Low
I want to generate a SQL statement that outputs counts for each column, it would hopefully look like the following: 我想生成一条输出每列计数的SQL语句,希望它看起来像下面的样子:
Priority | SSM | Abortion | Climate |
High 2 2 1
Medium 1 0 1
Low 1 1 2
A relatively simple way that works in any database is to use union all
: 在任何数据库中工作的相对简单的方法是使用
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;
In most databases, you can combine this to: 在大多数数据库中,您可以将其组合为:
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;
I accepted @Gordon Linoffs answer since is the answer to the question. 我接受@Gordon Linoffs的答案,因为这是问题的答案。 But Strawberry got me thinking that I had conceptualized the problem wrong.
但是草莓让我想到我把问题概念化了。 What I needed to do was convert a wide dataset into a long, and then do the counting.
我需要做的是将一个宽数据集转换成一个长数据集,然后进行计数。 I got this from Using PIVOT to Flip Data from Wide to Tall
我是从使用PIVOT将数据从宽到高翻转的
To do this for my example: 以我的示例为例:
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
Maybe there's an easier way to do this, but data.world doesn't support CROSS APPLY 也许有一种更简单的方法可以做到这一点,但是data.world不支持CROSS APPLY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.