简体   繁体   中英

How to count rows matching a filter in aggregate operations

Sorry for the not punctual title, this is the best I succeeded to obtain.

I have a table like this:

       date          |  type   |  qty
2018-03-21 03:30:00  |   A     |   3
2018-03-22 03:30:00  |   A     |   3
2018-03-22 04:57:00  |   A     |   1
2018-03-22 05:18:00  |   B     |   3

I do some aggregations on this table, eg sum of qty over day or over month. In the same query I need to count how many rows are of type B, while retrieving the total qty on that day.

So,

select sum(qty), date_trunc('day', date) ... group by date_trunc('day', date);

Now, what I need to do next is to count how many rows are of type B. So the expected result is

   day      |   Bcount   |   totqty
2018-03-21  |     0      |    3
2018-03-22  |     1      |    7

I thought to use partitions but I'm not sure how to use them in this specific case.

Edit: thank you all, guys, for your answers. This was soooooooo easy 🙄

Use a case expression to do conditional aggregation :

select ...
       sum(case when type = 'B' then 1 else 0 end) as Bcount
...

Since 9.4 release we can replace the CASE WHEN clauses in these aggregate functions by the new FILTER clause , use below query:

select date_trunc('day', date) AS Day, 
Count(TYPE) filter (where Type = 'B') AS BCount,
Sum(qty) AS TotalQty
FROM Table1 group by date_trunc('day', date);

For Demo Follow the link:

http://sqlfiddle.com/#!17/a5203/14

Until Postgres 9.4 release , if you wanted to count a few sets of records when executing an aggregate function, you had to use a CASE WHEN . Like This:

SELECT date_trunc('day', date) AS Day, 
SUM(CASE WHEN TYPE = 'B' THEN 1 ELSE 0 END) AS BCount,
Sum(qty) AS TotalQty
FROM Table1 group by date_trunc('day', date);
select date_trunc('day', date) ,sum(qty),
SUM (CASE WHEN type = 'B' THEN 1 ELSE 0 END) AS Bcount
FROM Table1
group by date_trunc('day', date);

Demo

http://sqlfiddle.com/#!17/a5203/13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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