我的DateCompleted返回日期和时间。如果我想按日期分组并忽略时间。我该怎么做呢?
SELECT
Cast(Jobs.DateCompleted AS VarChar) AS 'DateCompleted',
SUM(Metrics.GB) AS GB,
SUM(Metrics.KB) AS KB
FROM Metrics
INNER JOIN Jobs ON Jobs.JobId = Metrics.JobId
INNER JOIN Projects ON Projects.ProjectId = Jobs.ProjectId
INNER JOIN JobTypes ON JobTypes.JobTypeId = Jobs.JobTypeId
WHERE Jobs.DateCompleted BETWEEN '12/01/2012' AND '12/03/2012'
GROUP BY Jobs.DateCompleted
答案 0 :(得分:4)
如果您使用的是SQL Server,那么您可以使用剥离时间的格式将值转换为varchar
:
SELECT convert(char(10), Jobs.DateCompleted, 120) AS DateCompleted,
SUM(Metrics.GB) AS GB,
SUM(Metrics.KB) AS KB
FROM Metrics
INNER JOIN Jobs
ON Jobs.JobId = Metrics.JobId
INNER JOIN Projects
ON Projects.ProjectId = Jobs.ProjectId
INNER JOIN JobTypes
ON JobTypes.JobTypeId = Jobs.JobTypeId
WHERE Jobs.DateCompleted Between '12/01/2012' AND '12/03/2012'
GROUP BY convert(char(10), Jobs.DateCompleted, 120)
如果您使用的是SQL Server 2008+,则可以将该值转换为日期:
SELECT cast(Jobs.DateCompleted as date) AS DateCompleted,
SUM(Metrics.GB) AS GB,
SUM(Metrics.KB) AS KB
FROM Metrics
INNER JOIN Jobs
ON Jobs.JobId = Metrics.JobId
INNER JOIN Projects
ON Projects.ProjectId = Jobs.ProjectId
INNER JOIN JobTypes
ON JobTypes.JobTypeId = Jobs.JobTypeId
WHERE Jobs.DateCompleted Between '12/01/2012' AND '12/03/2012'
GROUP BY cast(Jobs.DateCompleted as date)
注意:我假设SQL Server基于您以前的标记
答案 1 :(得分:0)
编写一个剥离时间部分的表达式,并按此表达式进行分组...在Ms SQL Server中,您可以使用DateAdd(dd, datediff(dd, 0, myDatetime), 0)
每个RDBMS都有自己的函数或语法。对于Ms SQLServer,请参阅this SO question
答案 2 :(得分:0)
答案是您将日期时间显式转换为日期(如果日期是受支持的数据类型)或隐式(转换为字符串)。
ANSI标准方法是执行以下操作:
select extract(year from jobs.DateCompleted),
extract(month from jobs.DateCompleted),
extract(day from jobs.DateCompleted),
. . .
group by extract(year from jobs.DateCompleted),
extract(month from jobs.DateCompleted),
extract(day from jobs.DateCompleted)
但是从来没有这样做过。在最新版本的SQL Server中,您将使用cast(jobs.DateCompleted as date)
。在MySQL中,date(jobs.DateCompleted)
。在Oracle中,我会to_char(jobs.DateCompleted, 'YYYY-MM-DD')
。
答案 3 :(得分:0)
你还没有指定rdbms,所以这是一个疯狂的猜测。
如果您使用的是SQL Server,则可以按日期时间的datepart
分组。
GROUP BY DATEPART(year, Jobs.DateCompleted),
DATEPART(month, Jobs.DateCompleted),
DATEPART(day, Jobs.DateCompleted)