How can I make “month” columns in Sql?

后端 未结 6 835
轻奢々
轻奢々 2020-12-17 01:44

I\'ve got a set of data that looks something like this (VERY simplified):

productId    Qty   dateOrdered
---------    ---   -----------
       1             


        
6条回答
  •  离开以前
    2020-12-17 02:06

    This qualifies as a presentation concern.
    Presentation and SQL don't always mix well.

    Isolating your presentation logic in the application layer will:

    1. save you maintenance time—change your application code, but keep your SQL intact;
    2. enable you to more quickly adapt to ephemeral client requirements;
    3. give you more satisfaction than fiddling with a cross-tab or pivot-table that maddeningly does almost exactly what you want.

    Below is an example of how you might 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
    

提交回复
热议问题