简体   繁体   English

使用计数案例

[英]Using Count case

So I've been just re-familiarizing myself with SQL after some time away from it, and I am using Mode Analytics sample Data warehouse, where they have a dataset for SF police calls in 2014. 因此,我离开SQL一段时间后才重新熟悉SQL,我使用的是Mode Analytics示例数据仓库,该仓库在2014年有一个供SF警察呼叫的数据集。

For reference, it's set up as this: 作为参考,它设置如下:

incident_num, category, descript, day_of_week, date, time, pd_district, Resolution, address, ID

What I am trying to do is figure out the total number of incidents for a category, and a new column of all the people who have been arrested. 我要做的是找出某个类别的事件总数,并在所有被捕人员中增加一个新的列。 Ideally looking something like this 理想地看起来像这样

Category,  Total_Incidents,  Arrested
-------------------------------------
Battery         10              4
Murder          200             5

Something like that.. 像这样

So far I've been trying this out: 到目前为止,我一直在尝试:

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

That returns the total amount of incidents correctly, but for the Arrested, it keeps printing out 9014 Arrest 这样可以正确返回事件总数,但是对于“被捕”,它将继续打印出9014“被捕”

Any idea what I am doing wrong? 知道我在做什么错吗?

The subquery is not correlated. 子查询不相关。 It just selects the count of all rows. 它只是选择所有行的计数。 Add a condition, that checks for the category to be equal to that of the outer query. 添加一个条件,该条件检查类别是否等于外部查询的类别。

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

You could use this: 您可以使用此:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM