Question: I rarely write SQL (Azure SQL) however I am trying to generate a per month sales total per customer.

Customer:

```
    |Username     |ID    |
    |user1        |1     |
    |user2        |2     |
    |user3        |3     |

```

Order:

```
    |CustomerId   |Month |Total     |
    |1            |1     |275       |
    |1            |1     |10        |
    |2            |1     |100       |
    |1            |3     |150       |
    |2            |2     |150       |
    |2            |2     |65        |
    |3            |2     |150       |

```

I want to produce

```
|Username     |Month1Total |Month2Total | Month3Total |
|user1        |285         |275         |     150     |
|user2        |100         |215         |      0      |
|user3        |0           |150         |      0      |

```

I can do the following

```
SELECT customerTable.Username Username, SUM(orderTable.OrderTotal) TotalMay
FROM "Order" orderTable
JOIN Customer customerTable ON orderTable.CustomerId = customerTable.Id
WHERE DATENAME(Month, (orderTable.PaidDateUTC)) = 'May'
GROUP BY Username

```

Which will give me an output per month. However I don't know how to loop this, do it per month and then group by username.

Answer: 
you can use case when 

```
  with t1 as
   ( select o.CustomerId,o.Month, sum(Total) as total from
      [Order] 
     group by o.CustomerId,o.Month
  ) select c.Username, 
   case when t1.month=1 then t1.total else 0 end month1,
   case when t1.month=2 then t1.total else 0 end month2,
   case when t1.month=3 then t1.total else 0 end month3 
   from t1 join Customer c on t1.CustomerId=c.ID

```

Or you can use PIVOT

```
select c.username, t.* from
(
select * from 
(select * from ord
) src
pivot
( sum(Total) FOR Month IN ([1],[2],[3])
) pvt
) as t join Customer c on t.CustomerId=c.ID

```
I would simply do `JOIN` with conditional aggregation :

```
SELECT c.Username, 
       SUM(CASE WHEN o.Month = 1 THEN o.Total ELSE 0 END) AS [Month1Total],
       SUM(CASE WHEN o.Month = 2 THEN o.Total ELSE 0 END) AS [Month2Total],
       SUM(CASE WHEN o.Month = 3 THEN o.Total ELSE 0 END) AS [Month3Total],
       . . . 
FROM Customer C INNER JOIN
     Order o
     ON o.CustomerId = c.id
GROUP BY c.Username;

```