按其他列分组并计算出现次数

Group by and count apperances in other column

我的 table 看起来像这样:

----------------------------------------------
|id    | action   |  building   | date       |
----------------------------------------------
|1     | IN       | 1000        | 01-01-2015 |
|2     | OUT      | 1000        | 01-01-2015 |
|3     | OUT      | 1000        | 05-01-2015 |
|4     | IN       | 2000        | 01-01-2015 |
----------------------------------------------

我想通过构建和计算存在多少 IN 和 OUT 操作来对结果进行分组。数据和 id 在结果中无关紧要。结果应该是这样的:

-------------------------
| Building   | IN | OUT |
-------------------------
| 1000       | 1  | 2   |
| 2000       | 1  | 0   |
-------------------------

操作列只能包含 IN 和 OUT。

我最好的尝试是:

select distinct (action), building, count(*)
from table
group by action, building

输出:

-------------------------------------
| action     | Building  | count(*) |
-------------------------------------
| IN         | 1000      | 1        |
| OUT        | 1000      | 2        |
| IN         | 2000      | 1        |
-------------------------------------

用条件聚合来做:

select Building,
       sum(case when action = 'IN' then 1 else 0 end) as [IN],
       sum(case when action = 'OUT' then 1 else 0 end) as [OUT],
from TableName
group by Building

您需要使用条件聚合:

select building, 
       count(CASE WHEN action = 'IN' THEN 1 END) AS 'IN',
       count(CASE WHEN action = 'OUT' THEN 1 END) AS 'OUT'
from table
group by building