[英]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. 在同一查询中,我需要计算出B类型的行数,同时检索当天的总数量。
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 现在,我接下来要做的是计算B类型的行数。因此预期结果是
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 : 使用case
表达式进行条件聚合 :
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: 从9.4版本开始,我们可以用新的FILTER clause
替换这些聚合函数中的CASE WHEN
FILTER clause
,请使用以下查询:
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 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
. 在Postgres 9.4发行之前 ,如果要在执行聚合函数时计算几组记录,则必须使用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 http://sqlfiddle.com/#!17/a5203/13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.