PostgreSQL查询将列值分组为列

时间:2018-10-29 22:49:42

标签: postgresql group-by aggregate aggregate-functions

我有如下所示的PostreSQL表。 ordered是布尔值列,而created_at是时间戳记。我正在尝试获取行,这些行告诉我成功订单的总数(count(t))与失败订单的总数(count(f))以及按天分组的订单总数(t + f)(从created_at中提取)

ordered | created_at t | 2018-10-10 20:13:10 t | 2018-10-10 21:23:11 t | 2018-10-11 06:33:52 f | 2018-10-11 13:13:33 f | 2018-10-11 19:17:11 f | 2018-10-12 00:53:01 f | 2018-10-12 05:14:41 f | 2018-10-12 16:33:09 f | 2018-10-13 17:14:14

我想要以下结果

created_at | ordered_true | ordered_false | total_orders 2018-10-10 | 2 | 0 | 2 2018-10-11 | 1 | 2 | 3 2018-10-12 | 0 | 3 | 3 2018-10-13 | 0 | 1 | 1

2 个答案:

答案 0 :(得分:2)

使用聚合函数sum()count()

select 
    created_at::date, 
    sum(ordered::int) as ordered_true,
    sum((not ordered)::int) as ordered_false,
    count(*) as total_orders
from my_table
group by 1
order by 1

 created_at | ordered_true | ordered_false | total_orders 
------------+--------------+---------------+--------------
 2018-10-10 |            2 |             0 |            2
 2018-10-11 |            1 |             2 |            3
 2018-10-12 |            0 |             3 |            3
 2018-10-13 |            0 |             1 |            1
(4 rows)

答案 1 :(得分:0)

尝试:

SELECT created_at, 
       COUNT(ordered) filter (where ordered = 't') AS ordered_true,
       COUNT(ordered) filter (where ordered = 'f') AS ordered_false, 
       COUNT(*) AS total_orders 
FROM my_table
GROUP BY created_at

编辑:使用@klint的答案(按创建者OP分组的注释中所指出的那样)将导致不想要的结果,因为一天将有几组(时间戳超过一天)