SQL - 分组时聚合函数的condtion

时间:2016-10-22 13:50:16

标签: sql postgresql

表1

person    | zipcode     | timestamp               | event  | device
--------------------------------------------------|--------|------
amar      | 11111       | 2016-09-28 20:05:03.001 | email  | phone
akbar     | 11111       | 2016-09-28 20:05:03.001 | email  | phone  
antony    | 11111       | 2016-09-28 20:07:03.001 | chat   | pc
amar      | 11111       | 2016-09-28 20:08:03.001 | email  | phone
amar      | 11111       | 2016-09-28 20:08:03.001 | chat   | phone
amar      | 22222       | 2016-09-28 20:09:03.001 | email  | phone
akbar     | 22222       | 2016-09-28 20:10:03.001 | email  | phone  
antony    | 22222       | 2016-09-28 20:10:03.001 | chat   | phone
amar      | 11111       | 2016-09-28 21:05:03.001 | email  | phone
akbar     | 11111       | 2016-09-28 21:05:03.001 | email  | phone  
antony    | 11111       | 2016-09-28 21:07:03.001 | chat   | phone

输出所需

 person    | total_events | email_events 
 ---------------------------------------
 amar       | 5           | 4
 akbar      | 3           | 3
 antony     | 3           | 0

如下所示考虑使用group by - 如何获取event = 'email'这里的事件计数 - 是否有办法在不使用子选择的情况下执行此操作?

select
  person
  , count (*) as total_events
from table1
group by person

2 个答案:

答案 0 :(得分:3)

Protected Sub BTAddNew_Click(sender As Object, e As EventArgs) Handles BTAddNew.Click Try CheckImag() Insert() Catch ex As Exception MsgBox(ex.Message) End Try End Sub 语句中添加条件并将其包装在CASE聚合

试试这个

COUNT

答案 1 :(得分:2)

使用select person , count (*) as total_events , Count(case when event = 'email' then 1 end) as email_events from table1 group by person group by

case

在Postgres中,您可以将其缩短为:

select person,
       count(*) as total_events,
       sum(case when event = 'email' then 1 else 0 end) as email_events
from table1
group by person;