简体   繁体   English

MySQL在一个查询中有两个计数

[英]mySQL two counts in one query

I want to count the total number of accidents per year and the amount of car accidents happening per year separately. 我想分别计算每年的事故总数和每年发生的车祸数量。 My code however, it seems to only count the total number of accidents. 但是,我的代码似乎只计算事故总数。

So far my code is: 到目前为止,我的代码是:

Select Year, Count(*) AS 'Total', Count(*) AS 'Car' 
FROM ACCIDENTS 
WHERE Car = 1 
GROUP BY Year, Car 
Order BY Year ASC;

Table should be something like this: 表应该是这样的:

Year |  Accidents | Car
1990      500        25
1991      521        18

Structure of table: 表的结构:

在此处输入图片说明

I would count the years for the total amount of accidents and then the types of accidents would have boolean values to represent whether it was that type of accident. 我会计算事故总数的年数,然后事故类型将具有布尔值来表示这是否是此类事故。

使用以下查询

Select Year, Count(*) AS 'Total', count(case when car =1 then 1 else null end) FROM ACCIDENTS GROUP BY Year Order BY Year ASC;

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

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