I'm checking number of orders of by-franchise-operated or self-operated shops for a company. They are put into a date difference category. Here is the query and result as an explanation:
SELECT [Order-Delivery Difference], [Type], COUNT(DISTINCT OrderId) AS [Number of Orders]
FROM (SELECT DDIFF AS [Order-Delivery Difference], Franchise AS [Type], OrderId, [Net Value]
FROM joined
GROUP BY DDIFF, FRANCHISE, OrderId, [Net Value]
) AS subquery
GROUP BY [Order-Delivery Difference], [Type]
HAVING SUM([Net Value]) > 0
ORDER BY [Order-Delivery Difference]
;
I have a Date type column in my table, let's call it DateColumn. I can theoretically filter this result by any given specific time.
...
(SELECT DDIFF AS [Order-Delivery Difference], Franchise AS [Type], OrderId, [Net value]
FROM joined
WHERE DATEPART(year, [DateColumn]) = 2017 AND DATEPART(month, [DateColumn]) = 1
GROUP BY DDIFF, FRANCHISE, OrderId, [Net Value]
) AS subquery
...
But I want to pivot this result for every distinct month date available in the Date column, like this:
My questions are: Can I create a pivot table like this, having another column at the beggining? Or should I create a pivot table for every distinct O-D Difference category instead? Is there a practical way to do that?
Also is there a procedural solution to create a column with all the distinct month dates to give that as a dynamic attribute set for the pivot function?



