Zain Zafar
Zain Zafar

Reputation: 527

PostgreSQL Query for grouping column values into columns

I have the PostreSQL table shown below. ordered is a boolean column and created_at is a timestamp. I'm trying to fetch rows which tell me the total number of successful orders (count(t)) vs failed ordered (count(f)) as well as the total number of orders (t + f) grouped by day (extracted from 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

I want the following result

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

Upvotes: 4

Views: 2446

Answers (2)

ArdentLearner
ArdentLearner

Reputation: 732

Try:

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

EDIT: use @klint's answer as pointed in the comments by OP grouping by created_at will result in unwanted results as one day will have a couple of groups(timestamp longer than just a day)

Upvotes: 1

klin
klin

Reputation: 121474

Use the aggregate functions sum() and 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)

Upvotes: 4

Related Questions