使用计数案例
Using Count case
所以我在离开它一段时间后才重新熟悉 SQL,我正在使用 Mode Analytics 示例数据仓库,他们在 2014 年有一个 SF 报警电话的数据集。
作为参考,设置如下:
incident_num, category, descript, day_of_week, date, time, pd_district, Resolution, address, ID
我想做的是计算一个类别的事件总数,以及所有被捕人员的新列。理想情况下看起来像这样
Category, Total_Incidents, Arrested
-------------------------------------
Battery 10 4
Murder 200 5
类似的..
到目前为止我一直在尝试这个:
SELECT category, COUNT (Resolution) AS Total_Incidents, (
Select COUNT (resolution)
from tutorial.sf_crime_incidents_2014_01
where Resolution like '%ARREST%') AS Arrested
from tutorial.sf_crime_incidents_2014_01
group by 1
order by 2 desc
那个returns事件总数正确,但是对于Arrested,它一直打印出9014 Arrest
知道我做错了什么吗?
子查询不相关。它只是选择所有行的计数。添加一个条件,检查类别是否等于外部查询的类别。
SELECT o.category,
count(o.resolution) total_incidents,
(SELECT count(i.resolution)
FROM tutorial.sf_crime_incidents_2014_01 i
WHERE i.resolution LIKE '%ARREST%'
AND i.category = o.category) arrested
FROM tutorial.sf_crime_incidents_2014_01 o
GROUP BY 1
你可以使用这个:
SELECT category,
COUNT(Resolution) AS Total_Incidents,
SUM(CASE WHEN Resolution LIKE '%ARREST%' THEN 1 END) AS Arrested
FROM tutorial.sf_crime_incidents_2014_01
GROUP BY category
ORDER BY 2 DESC;
所以我在离开它一段时间后才重新熟悉 SQL,我正在使用 Mode Analytics 示例数据仓库,他们在 2014 年有一个 SF 报警电话的数据集。
作为参考,设置如下:
incident_num, category, descript, day_of_week, date, time, pd_district, Resolution, address, ID
我想做的是计算一个类别的事件总数,以及所有被捕人员的新列。理想情况下看起来像这样
Category, Total_Incidents, Arrested
-------------------------------------
Battery 10 4
Murder 200 5
类似的..
到目前为止我一直在尝试这个:
SELECT category, COUNT (Resolution) AS Total_Incidents, (
Select COUNT (resolution)
from tutorial.sf_crime_incidents_2014_01
where Resolution like '%ARREST%') AS Arrested
from tutorial.sf_crime_incidents_2014_01
group by 1
order by 2 desc
那个returns事件总数正确,但是对于Arrested,它一直打印出9014 Arrest
知道我做错了什么吗?
子查询不相关。它只是选择所有行的计数。添加一个条件,检查类别是否等于外部查询的类别。
SELECT o.category,
count(o.resolution) total_incidents,
(SELECT count(i.resolution)
FROM tutorial.sf_crime_incidents_2014_01 i
WHERE i.resolution LIKE '%ARREST%'
AND i.category = o.category) arrested
FROM tutorial.sf_crime_incidents_2014_01 o
GROUP BY 1
你可以使用这个:
SELECT category,
COUNT(Resolution) AS Total_Incidents,
SUM(CASE WHEN Resolution LIKE '%ARREST%' THEN 1 END) AS Arrested
FROM tutorial.sf_crime_incidents_2014_01
GROUP BY category
ORDER BY 2 DESC;