SQL query to group by day

后端 未结 8 1985
感动是毒
感动是毒 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:30

    use linq

    from c in Customers
    group c by DbFunctions.TruncateTime(c.CreateTime) into date
    orderby date.Key descending
    select new  
    {
        Value = date.Count().ToString(),
        Name = date.Key.ToString().Substring(0, 10)
    }
    
    0 讨论(0)
  • 2020-12-04 09:36

    actually this depends on what DBMS you are using but in regular SQL convert(varchar,DateColumn,101) will change the DATETIME format to date (one day)

    so:

    SELECT 
        sum(amount) 
    FROM 
        sales 
    GROUP BY 
        convert(varchar,created,101)
    

    the magix number 101 is what date format it is converted to

    0 讨论(0)
  • 2020-12-04 09:40

    if you're using SQL Server,

    dateadd(DAY,0, datediff(day,0, created)) will return the day created

    for example, if the sale created on '2009-11-02 06:12:55.000', dateadd(DAY,0, datediff(day,0, created)) return '2009-11-02 00:00:00.000'

    select sum(amount) as total, dateadd(DAY,0, datediff(day,0, created)) as created
    from sales
    group by dateadd(DAY,0, datediff(day,0, created))
    
    0 讨论(0)
  • 2020-12-04 09:44

    For PostgreSQL:

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

    or using cast:

    GROUP BY timestampfield::date
    

    if you want speed, use the second option and add an index:

    CREATE INDEX tablename_timestampfield_date_idx ON  tablename(date(timestampfield));
    
    0 讨论(0)
  • 2020-12-04 09:45

    If you're using MySQL:

    SELECT
        DATE(created) AS saledate,
        SUM(amount)
    FROM
        Sales
    GROUP BY
        saledate
    

    If you're using MS SQL 2008:

    SELECT
        CAST(created AS date) AS saledate,
        SUM(amount)
    FROM
        Sales
    GROUP BY
        CAST(created AS date)
    
    0 讨论(0)
  • 2020-12-04 09:48

    For oracle you can

    group by trunc(created);
    

    as this truncates the created datetime to the previous midnight.

    Another option is to

    group by to_char(created, 'DD.MM.YYYY');
    

    which achieves the same result, but may be slower as it requires a type conversion.

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