我想列出所有销售,并按天分组。
Sales (saleID INT, amount INT, created DATETIME)
更新的 我正在使用SQL Server 2005
答案 0 :(得分:139)
如果您使用的是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))
答案 1 :(得分:92)
对于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)
或更好(来自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)
答案 2 :(得分:32)
如果您使用的是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)
答案 3 :(得分:6)
实际上这取决于您使用的DBMS,但在常规SQL convert(varchar,DateColumn,101)
中会将DATETIME格式更改为日期(一天)
这样:
SELECT
sum(amount)
FROM
sales
GROUP BY
convert(varchar,created,101)
magix编号101
是转换为
答案 4 :(得分:6)
如果您正在使用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
这些计算字段将始终保持最新(当“创建”日期更改时),它们是表格的一部分,它们可以像常规字段一样使用,甚至可以编入索引(如果它们是“PERSISTED”) - 这个功能完全未被充分利用,恕我直言。
马克
答案 5 :(得分:2)
对于oracle你可以
group by trunc(created);
因为这会将创建的日期时间截断到上一个午夜。
另一种选择是
group by to_char(created, 'DD.MM.YYYY');
可以获得相同的结果,但可能会因为需要进行类型转换而变慢。
答案 6 :(得分:0)
对于PostgreSQL:
GROUP BY to_char(timestampfield, 'yyyy-mm-dd')
或使用演员:
GROUP BY timestampfield::date
如果您想要速度,请使用第二个选项并添加索引:
CREATE INDEX tablename_timestampfield_date_idx ON tablename(date(timestampfield));
答案 7 :(得分:-2)
使用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)
}