SQL Server 按天分组的SQL查询

gk7wooem  于 2023-01-12  发布在  其他
关注(0)|答案(9)|浏览(210)

我想列出所有的销售额,并按天将总数分组。

Sales (saleID INT, amount INT, created DATETIME)

注意:我使用的是SQL Server 2005。

g52tjvyc

g52tjvyc1#

如果你用的是SQL Server
dateadd(DAY,0, datediff(day,0, created))将返回创建日期
例如,如果销售创建于'2009-11-02 06:12:55.000',则dateadd(DAY,0, datediff(day,0, created))返回'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))
wn9m85ua

wn9m85ua2#

对于SQL Server:

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

或更快(来自Q8-Coder):

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

对于MySQL:

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

或更好(来自乔恩·布莱特):

GROUP BY date(datefield)

对于Oracle:

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

或更快(来自IronGoofy):

GROUP BY trunc(created);

对于Informix(作者:Jonathan Leffler):

GROUP BY date_column
GROUP BY EXTEND(datetime_column, YEAR TO DAY)
mrwjdhj3

mrwjdhj33#

如果您使用MySQL:

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

如果您使用的是MS SQL 2008:

SELECT
    CAST(created AS date) AS saledate,
    SUM(amount)
FROM
    Sales
GROUP BY
    CAST(created AS date)
1u4esq0p

1u4esq0p4#

对于PostgreSQL:

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

或使用cast:

GROUP BY timestampfield::date

如果你想要速度,使用第二个选项并添加一个索引:

CREATE INDEX tablename_timestampfield_date_idx ON  tablename(date(timestampfield));
icomxhvb

icomxhvb5#

实际上,这取决于您使用的DBMS,但在常规SQL convert(varchar,DateColumn,101)中,DATETIME格式将更改为日期(一天)
因此:

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

magix编号101是它被转换成的日期格式

8wigbo56

8wigbo566#

如果使用的是SQL Server,则可以向表中添加三个计算字段:

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

现在,您可以轻松地按销售的日、月或年进行分组、排序等:

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

这些计算字段将始终保持最新(当您的“创建”日期更改),他们是您的表的一部分,他们可以像常规字段一样使用,甚至可以索引(如果他们是“持久”)-伟大的功能,完全没有得到充分利用,恕我直言。
马克

bvn4nwqk

bvn4nwqk7#

对于oracle,您可以

group by trunc(created);

因为这将创建的日期时间截断到前一个午夜。
另一种选择是

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

这实现了相同的结果,但是由于其需要类型转换而可能较慢。

r3i60tvu

r3i60tvu8#

MySQL最简单直观的解决方案是:

GROUP BY day(datefield)
w80xi6nr

w80xi6nr9#

使用链接

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)
}

相关问题