This relates to the problem of presentation.
Presentation and SQL do not always mix well.
Isolation of presentation logic at the application level will be:
- save maintenance time - change application code, but keep your SQL intact;
- allow you to quickly adapt to the requirements of ephemeral clients;
- gives you more satisfaction than messing around with a crosstab or pivot table that madly does almost what you want.
Below is an example of how you can do this in Python (you can use the excellent pyodbc module to connect to SQL Server):
from collections import defaultdict from datetime import date dd = defaultdict(int) # input rows = [(1,2,date(2008,10,10)), (1,1,date(2008,11,10)), (1,2,date(2009,10,10)), (2,3,date(2009,10,12)), (1,1,date(2009,10,15)), (2,2,date(2009,11,15))] for row in rows: # row[0] == productId # row[1] == Qty # row[2] == dateOrdered # pyodbc enables referring to column names by name dd[(row[2].year, row[2].month, row[0])] += row[1] presentation_rows = sorted(set((i[0], i[2]) for i in dd.keys())) for i in presentation_rows: print i[1], i[0], for j in range(0,13): try: print dd[i[0], j, i[1]], except IndexError: print 0, print # output # 1 2008 0 0 0 0 0 0 0 0 0 0 2 1 0 # 1 2009 0 0 0 0 0 0 0 0 0 0 3 0 0 # 2 2009 0 0 0 0 0 0 0 0 0 0 3 2 0
bernie
source share