Sql查询分组按天
我想列出所有的销售,并按天分组。
Sales (saleID INT, amount INT, created DATETIME)
更新我正在使用SQL Server 2005
如果您使用的是SQL Server,
dateadd(DAY,0, datediff(day,0, created))
将返回创build的date
例如,如果在'2009-11-02 06:12:55.000'创build的销售, 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))
对于SQL Server:
GROUP BY datepart(year,datefield), datepart(month,datefield), datepart(day,datefield)
或更快(来自Q8编码器):
GROUP BY dateadd(DAY,0, datediff(day,0, created))
对于MySQL:
GROUP BY year(datefield), month(datefield), day(datefield)
或更好(来自Jon Bright):
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)
如果你使用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) AS saledate
如果您使用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
现在你可以很容易地根据销售的日,月,年等进行分组,sorting:
SELECT SaleDay, SUM(Amount) FROM dbo.Sales GROUP BY SaleDay
这些计算的字段将始终保持最新状态(当您的“创build”date更改时),它们是您的表的一部分,它们可以像常规字段一样使用,甚至可以被索引(如果它们是“持久化” ) – 这是完全没有用的很好的function,恕我直言。
渣子
实际上这取决于你正在使用什么DBMS,但在常规SQL convert(varchar,DateColumn,101)
将更改date(一天)的DATETIME格式,
所以:
SELECT sum(amount) FROM sales GROUP BY convert(varchar,created,101)
魔术数字101
是什么date格式转换为
对于甲骨文,你可以
group by trunc(created);
因为这会将创build的date时间截断到前一个午夜。
另一个select是
group by to_char(created, 'DD.MM.YYYY');
达到相同的结果,但是由于需要进行types转换可能会变慢。
对于PostgreSQL:
GROUP BY to_char(timestampfield, 'yyyy-mm-dd')
或使用演员:
GROUP BY timestampfield::date
如果你想速度,使用第二个选项,并添加一个索引:
CREATE INDEX tablename_timestampfield_date_idx ON tablename(date(timestampfield));
使用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) }