SQL Server Group By Month

前端 未结 7 1287
攒了一身酷
攒了一身酷 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:27

    I prefer combining DATEADD and DATEDIFF functions like this:

    GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0)
    

    Together, these two functions zero-out the date component smaller than the specified datepart (i.e. MONTH in this example).

    You can change the datepart bit to YEAR, WEEK, DAY, etc... which is super handy.

    Your original SQL query would then look something like this (I can't test it as I don't have your data set, but it should put you on the right track).

    DECLARE @start [datetime] = '2010-04-01';
    
    SELECT
        ItemID,
        UserID,
        DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0) [Month],
        IsPaid,
        SUM(Amount)
    FROM LIVE L
    INNER JOIN Payments I ON I.LiveID = L.RECORD_KEY
    WHERE UserID = 16178
    AND PaymentDate > @start
    

    One more thing: the Month column is typed as a DateTime which is also a nice advantage if you need to further process that data or map it .NET object for example.

提交回复
热议问题