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: 
IF you want to have a separate column for each month then try this 

```
SELECT customerTable.Username Username
,SUM(iif(ordertable.[month] = 1,orderTable.OrderTotal,0)) TotalJan
,SUM(iif(ordertable.[month] = 2,orderTable.OrderTotal,0)) TotalFeb
,SUM(iif(ordertable.[month] = 3,orderTable.OrderTotal,0)) TotalMar
,SUM(iif(ordertable.[month] = 4,orderTable.OrderTotal,0)) TotalApr
,SUM(iif(ordertable.[month] = 5,orderTable.OrderTotal,0)) TotalMay

FROM "Order" orderTable
JOIN Customer customerTable ON orderTable.CustomerId = customerTable.Id

GROUP BY Username

```

should be easy to add the remaining months
Something like this:

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

```

You just need to move the month name from the WHERE clause to the GROUP BY.