I have a bunch of orders for which I need to produce a report showing totals for each product group, by order.
For example:
Order Lines
Line Id, Order No., Product Id, Product Group Id, Quantity
1 , 1 , 1 , 1 , 5
2 , 1 , 2 , 2 , 3
3 , 2 , 1 , 1 , 5
4 , 3 , 3 , 1 , 1
5 , 3 , 1 , 1 , 5
6 , 4 , 3 , 1 , 4
...
1200 , 999 , 16 , 12 , 4
Should show
Order No., Group 1, Group 2, ..., Group 12, ..., Group N
1 , 5 , 3, , ..., 0 , ..., 0
2 , 5 , 0, , ..., 0 , ..., 0
3 , 6 , 0, , ..., 0 , ..., 0
4 , 4 , 0, , ..., 0 , ..., 0
999 , 0 , 0, , ..., 4 , ..., 0
Product groups are defined by the end user, hence I have put in the ...
and Group N
to signify I don't know how many columns will be in the end result.
The easy bit is grouping the order lines by product group...
SELECT OrderNo, ProductGroupId, SUM(Quantity)
FROM OrderLines
GROUP BY OrderNo, ProductGroupId
but then, how do I pivot that into the result format, when I don't know how many columns will be in the final SELECT
?
I'm using SQL Server 2019.