Search code examples
mysqlsqlinner-join

Join SQL table to divide one column into 3 columns with sum


Table "dsi" is split into 4 columns currently.

id | dsi | amount | month  
2  | debt| -23.39 | 02  
2  | debt| -27.32 | 02  
2  | sav |  23.39 | 03  
2  | inv | 101.39 | 04  
2  | sav |  23.39 | 04  
2  | debt| -42.42 | 04  
2  | sav | 123.39 | 03  
2  | inv |  23.39 | 03  
2  | sav | 231.39 | 04  
2  | inv | 234.39 | 04  

I would like to query the table by user (id column), month, and totals of debts, savings, and investments per month. Ideally, it would look something like this:

month |  debt  |  sav  |  inv  |  
02    | -50.71 |       |       |  
03    |        | 146.78| 23.39 |  
04    | -42.42 | 231.39|234.39 | 

I've tried so many different MySQL queries, including inner join but I'm not finding the correct method. What is the proper way to query this?

This is my most recent attempt:

cursor.execute("""SELECT a.month, debt, savings, investment   
        FROM dsi a INNER JOIN dsi b   
        ON a.month   
        ON a.dsi=d.dsi    
        GROUP BY a.month   
        SUM(amount) AS debt WHERE (dsi = %s) AND (id = %s) GROUP BY month""", ("debt", id))
data = cursor.fetchall()

Solution

  • Do you just want conditional aggregation?

    select month,
           sum(case when dsi = 'debt' then amount end) as debt,
           sum(case when dsi = 'sav' then amount end) as sav,
           sum(case when dsi = 'inv' then amount end) as inv
    from dsi
    group by month