1

我的 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
4

4 回答 4

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 基于您以前的标签

于 2012-12-04T15:17:19.717 回答
0

编写一个去除时间部分的表达式,并按此表达式分组......在 SQL Server 女士中,您可以使用DateAdd(dd, datediff(dd, 0, myDatetime), 0) 每个 RDBMS 都有其自己的函数或语法。对于 SQLServer 女士,请参阅此 SO 问题

于 2012-12-04T15:18:08.673 回答
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')

于 2012-12-04T15:20:00.967 回答
0

您还没有指定 rdbms,所以这是一个疯狂的猜测。

如果您使用的是 SQL Server,那么您可以按datepart日期时间的一部分进行分组。

GROUP BY DATEPART(year, Jobs.DateCompleted),
         DATEPART(month, Jobs.DateCompleted),
         DATEPART(day, Jobs.DateCompleted)
于 2012-12-04T15:34:39.060 回答