使用Count案例

时间:2018-05-21 04:04:50

标签: sql mode-analytics

所以我在离开它之后只是重新熟悉了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

正确返回事件的总数,但对于被捕,它会继续打印9014逮捕

知道我做错了吗?

2 个答案:

答案 0 :(得分:3)

子查询不相关。它只选择所有行的计数。添加一个条件,检查类别是否与外部查询的类别相同。

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

答案 1 :(得分:3)

你可以用这个:

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;