Search code examples
sqlsumverticacalculation

How do you get the sum of values by day, but day in columns SQL


I have a table that looks like below where day, client_name and order_value are stored/

select day, client_name, order_value
from sample_table
day client_name order_value
2021-01-01 A 100
2021-01-01 A 100
2021-01-02 A 200
2021-01-03 A 100
2021-01-01 B 300
2021-01-01 B 400
2021-01-01 C 500
2021-01-02 C 500
2021-01-02 C 500

and I want to get the sum of order_value per client by day, but days in columns. Basically, I want my result to come out something like this.

client_name 2021-01-01 2021-01-02 2021-01-03
A 200 200 100
B 700 Null Null
C 500 1000 Null

Solution

  • If you know what the days are, you can use conditional aggregation:

    select client_name,
           sum(case when date = '2021-01-01' then order_value end) as date_20210101,
           sum(case when date = '2021-01-02' then order_value end) as date_20210102,
           sum(case when date = '2021-01-03' then order_value end) as date_20210103
    from t
    group by client_name ;
    

    If you don't know the specific dates (i.e., you want them based on the data or a variable number), then you need to use dynamic SQL. That means that you construct the SQL statement as a string and then execute it.