How can I make “month” columns in Sql?

后端 未结 6 836
轻奢々
轻奢々 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:18

    select productId, Year(dateOrdered) Year
      ,isnull(sum(case when month(dateOrdered) = 1 then Qty end), 0) Jan
      ,isnull(sum(case when month(dateOrdered) = 2 then Qty end), 0) Feb 
      ,isnull(sum(case when month(dateOrdered) = 3 then Qty end), 0) Mar
      ,isnull(sum(case when month(dateOrdered) = 4 then Qty end), 0) Apr
      ,isnull(sum(case when month(dateOrdered) = 5 then Qty end), 0) May
      ,isnull(sum(case when month(dateOrdered) = 6 then Qty end), 0) Jun
      ,isnull(sum(case when month(dateOrdered) = 7 then Qty end), 0) Jul
      ,isnull(sum(case when month(dateOrdered) = 8 then Qty end), 0) Aug
      ,isnull(sum(case when month(dateOrdered) = 9 then Qty end), 0) Sep
      ,isnull(sum(case when month(dateOrdered) = 10 then Qty end), 0) Oct
      ,isnull(sum(case when month(dateOrdered) = 11 then Qty end), 0) Nov
      ,isnull(sum(case when month(dateOrdered) = 12 then Qty end), 0) Dec
    from Table1
    group by productId, Year(dateOrdered)
    

    SQL Fiddle

提交回复
热议问题