我想列出所有的销售,并按照日期分组的总和。
Sales (saleID INT, amount INT, created DATETIME)
我正在使用的SQL Server 2005
我想列出所有的销售,并按照日期分组的总和。
Sales (saleID INT, amount INT, created DATETIME)
我正在使用的SQL Server 2005
如果你使用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))
对于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)
或更好(乔恩亮):
GROUP BY date(datefield)
对于Oracle:
GROUP BY to_char(datefield, 'yyyy-mm-dd')
或更快(从IronGoofy):
GROUP BY trunc(created);
对于Informix(乔纳森·莱弗勒):
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)
其实这取决于你使用的,但在常规的SQL什么DBMS convert(varchar,DateColumn,101)
将改变DATETIME格式的日期(一天)
所以:
SELECT
sum(amount)
FROM
sales
GROUP BY
convert(varchar,created,101)
在MAGIX数字101
是什么日期格式,将它转换成
如果您使用的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
这些计算领域将始终保持最新状态(当你的“创建”日期的改变),他们是你的表的一部分,它们可以用来就像普通的领域,甚至可以建立索引(如果他们是“坚持” ) - 伟大的功能,是完全未充分利用的,恕我直言。
渣
对于Oracle,你可以
group by trunc(created);
因为这截断创建日期时间以前的午夜。
另一种选择是
group by to_char(created, 'DD.MM.YYYY');
其实现相同的结果,但是,因为它需要一个类型转换可能会比较慢。
对于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)
}