将日期/时间转换为日期

时间:2015-09-08 12:34:22

标签: sql-server sql-server-2005

我有一个运行的查询,我想返回日期大于或等于特定日期的记录。我要查询的列是日期时间格式。

SELECT COUNT(RSO_ParentID), AssignedDateTime
FROM Task
WHERE OwnerTeam='2nd Line Support' AND AssignedDateTime>='2015-09-01 00:00:00.000'
GROUP BY AssignedDateTime

有没有办法在AssignedDateTime的日期部分进行过滤,并相对于当前日期进行搜索(即搜索前7天)?

谢谢, 马特

4 个答案:

答案 0 :(得分:3)

你可以在MSSQL中这样做。

SELECT COUNT(RSO_ParentID), AssignedDateTime
FROM Task
WHERE OwnerTeam='2nd Line Support' AND AssignedDateTime>=DATEADD(D,-7, GETDATE())
GROUP BY AssignedDateTime

答案 1 :(得分:2)

注意:当我回答这个问题时,这个问题没有被标记为SQL Server 2005。我将离开答案,因为它适用于SQL Server 2008 +。

如果您只关心日期而不是时间,则需要结合使用和WITH CTE_ABC AS ( SELECT DISTINCT NUMM FROM [Table] ) ,CTE_XYZ AS ( SELECT * FROM ( SELECT NUMM ,lead(NUMM) OVER ( ORDER BY NUMM ) AS numm1 FROM CTE_ABC ) A WHERE numm1 IS NOT NULL ) SELECT A.NUMM ,B.numm1 FROM [Table] A LEFT JOIN CTE_XYZ B ON A.columnId = B.columnId WHERE B.numm1 IS NOT NULL

datediff()

请注意,您也可以使用SELECT COUNT(RSO_ParentID), AssignedDateTime FROM Task WHERE OwnerTeam = '2nd Line Support' AND AssignedDateTime >= dateadiff(day, -7, cast(getdate() as date)) GROUP BY AssignedDateTime; 上的功能表达此信息。这通常是个坏主意,因为它通常会阻止查询使用索引。

我也猜测你想要白天的结果:

AssignedDateTime

或总计,您不需要SELECT COUNT(RSO_ParentID), cast(AssignedDateTime as date) FROM Task WHERE OwnerTeam = '2nd Line Support' AND AssignedDateTime >= dateadiff(day, -7, cast(getdate() as date)) GROUP BY cast(AssignedDateTime as date); 子句:

group by

答案 2 :(得分:0)

如果您使用的是MSSQL,请使用DATEDIFF。

SELECT COUNT(RSO_ParentID), AssignedDateTime
FROM Task
WHERE OwnerTeam='2nd Line Support' AND DATEDIFF(DAY,AssignedDateTime,GETDATE()) <=7
GROUP BY AssignedDateTime

答案 3 :(得分:0)

试试这个,它只会检查日期部分,而不是时间部分

ng-repeat