SQL Server Group By Month

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

    Another approach, that doesn't involve adding columns to the result, is to simply zero-out the day component of the date, so 2016-07-13 and 2016-07-16 would both be 2016-07-01 - thus making them equal by month.

    If you have a date (not a datetime) value, then you can zero it directly:

    SELECT
        DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] ),
        COUNT(*)
    FROM
        [Table]
    GROUP BY
        DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] )
    

    If you have datetime values, you'll need to use CONVERT to remove the time-of-day portion:

    SELECT
        DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) ),
        COUNT(*)
    FROM
        [Table]
    GROUP BY
        DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) )
    
    0 讨论(0)
提交回复
热议问题