SQL Server Group By Month

前端 未结 7 1279
攒了一身酷
攒了一身酷 2020-12-13 01:53

I have a table which has this schema

ItemID    UserID    Year    IsPaid    PaymentDate  Amount
1         1         2009    0         2009-11-01  300
2                


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 02:13

    Now your query is explicitly looking at only payments for year = 2010, however, I think you meant to have your Jan/Feb/Mar actually represent 2009. If so, you'll need to adjust this a bit for that case. Don't keep requerying the sum values for every column, just the condition of the date difference in months. Put the rest in the WHERE clause.

    SELECT 
          SUM( case when DateDiff(m, PaymentDate, @start) = 0 
               then Amount else 0 end ) AS "Apr",
          SUM( case when DateDiff(m, PaymentDate, @start) = 1 
               then Amount else 0 end ) AS "May",
          SUM( case when DateDiff(m, PaymentDate, @start) = 2 
               then Amount else 0 end ) AS "June",
          SUM( case when DateDiff(m, PaymentDate, @start) = 3 
               then Amount else 0 end ) AS "July",
          SUM( case when DateDiff(m, PaymentDate, @start) = 4 
               then Amount else 0 end ) AS "Aug",
          SUM( case when DateDiff(m, PaymentDate, @start) = 5 
               then Amount else 0 end ) AS "Sep",
          SUM( case when DateDiff(m, PaymentDate, @start) = 6 
               then Amount else 0 end ) AS "Oct",
          SUM( case when DateDiff(m, PaymentDate, @start) = 7 
               then Amount else 0 end ) AS "Nov",
          SUM( case when DateDiff(m, PaymentDate, @start) = 8 
               then Amount else 0 end ) AS "Dec",
          SUM( case when DateDiff(m, PaymentDate, @start) = 9 
               then Amount else 0 end ) AS "Jan",
          SUM( case when DateDiff(m, PaymentDate, @start) = 10 
               then Amount else 0 end ) AS "Feb",
          SUM( case when DateDiff(m, PaymentDate, @start) = 11 
               then Amount else 0 end ) AS "Mar"
       FROM 
          Payments I
             JOIN Live L
                on I.LiveID = L.Record_Key
       WHERE 
              Year = 2010 
          AND UserID = 100
    

提交回复
热议问题