Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 839
Zain Zafar Avatar asked Sep 01 '25 03:09

Zain Zafar


1 Answers

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)
like image 84
klin Avatar answered Sep 02 '25 17:09

klin