所以我有这个简单的聚合函数,它使用date_trunc
方法给我所需的精度水平,但我需要在聚合中包含具有特定条件的列的总和。
让你知道我想要什么
SELECT
COUNT( comments )
,COUNT( likes )
,COUNT( something_else )
,date_trunc( 'minute' ,date )
FROM
events
GROUP BY
date_trunc( 'minute' ,date );
comments
,likes
和something_else
将成为事件的派生表,其中列name = commnt
(这就是我需要帮助的部分)
修改
样本表和所需的输出
____________________
| date | type |
|2015-6-1| post |
|2015-6-1| comment |
|2015-6-2| comment |
|2015-6-2| post |
|2015-6-2| pm |
|2015-6-2| comment |
|2015-6-3| pm |
应输出
| date | num_post | num_comment | num_pm |
|2015-6-1| 1 | 1 | 0 |
|2015-6-2| 1 | 2 | 1 |
|2015-6-3| 0 | 0 | 1 |
答案 0 :(得分:1)
我制作了一张与你匹配的测试数据表:
event | type
------------+---------
2015-06-01 | comment
2015-06-01 | post
2015-06-02 | comment
2015-06-02 | comment
2015-06-02 | pm
2015-06-02 | post
2015-06-03 | pm
(7 rows)
然后运行
select event, sum((type='post')::int) as posts,
sum((type='comment')::int) as comments,
sum((type='pm')::int) as pms
from exp
group by event
order by event
让我
event | posts | comments | pms
------------+-------+----------+-----
2015-06-01 | 1 | 1 | 0
2015-06-02 | 1 | 2 | 1
2015-06-03 | 0 | 0 | 1
(3 rows)
我们从type = ...
比较中获得了一堆布尔值,并将它们转换为int使得我们0为假,而1对于trues,我们可以将它们总结为得到你正在寻找的答案。