SQL query to group by day

后端 未结 8 1986
感动是毒
感动是毒 2020-12-04 09:21

I want to list all sales, and group the sum by day.

Sales (saleID INT, amount INT, created DATETIME)

NOTE: I am using SQL Server 2005.

相关标签:
8条回答
  • 2020-12-04 09:50

    For SQL Server:

    GROUP BY datepart(year,datefield), 
        datepart(month,datefield), 
        datepart(day,datefield)
    

    or faster (from Q8-Coder):

    GROUP BY dateadd(DAY,0, datediff(day,0, created))
    

    For MySQL:

    GROUP BY year(datefield), month(datefield), day(datefield)
    

    or better (from Jon Bright):

    GROUP BY date(datefield)
    

    For Oracle:

    GROUP BY to_char(datefield, 'yyyy-mm-dd')
    

    or faster (from IronGoofy):

    GROUP BY trunc(created);
    

    For Informix (by Jonathan Leffler):

    GROUP BY date_column
    GROUP BY EXTEND(datetime_column, YEAR TO DAY)
    
    0 讨论(0)
  • 2020-12-04 09:51

    If you're using SQL Server, you could add three calculated fields to your table:

    Sales (saleID INT, amount INT, created DATETIME)
    
    ALTER TABLE dbo.Sales
      ADD SaleYear AS YEAR(Created) PERSISTED
    ALTER TABLE dbo.Sales
      ADD SaleMonth AS MONTH(Created) PERSISTED
    ALTER TABLE dbo.Sales
      ADD SaleDay AS DAY(Created) PERSISTED
    

    and now you could easily group by, order by etc. by day, month or year of the sale:

    SELECT SaleDay, SUM(Amount)
    FROM dbo.Sales
    GROUP BY SaleDay
    

    Those calculated fields will always be kept up to date (when your "Created" date changes), they're part of your table, they can be used just like regular fields, and can even be indexed (if they're "PERSISTED") - great feature that's totally underused, IMHO.

    Marc

    0 讨论(0)
提交回复
热议问题