我正在尝试编写一个类似下面示例的SQL查询,但是,我需要它始终在当天的上午8:00和当天的下午4:00之间选择DateEntered字段。不知道该怎么做。有人可以帮忙吗?
SELECT OrderNumber
, OrderRelease
, HeatNumber
, HeatSuffix
, Operation
, COUNT(Operation) AS [Pieces Out of Tolerance]
FROM Alerts
WHERE (Mill = 3)
AND (DateEntered BETWEEN GetDate '08:00' AND GetDate '16:00')
GROUP BY OrderNumber, OrderRelease, HeatNumber, HeatSuffix, Operation
答案 0 :(得分:3)
DECLARE @TodayODBC varchar(30), @DateFrom datetime, @DateTo datetime
SET @TodayODBC = CONVERT(varchar(10), GETDATE(), 120)
SET @DateFrom = CONVERT(datetime, @TodayODBC + ' 08:00:00', 120)
SET @DateTo = CONVERT(datetime, @TodayODBC + ' 16:00:00', 120)
SELECT OrderNumber, OrderRelease, HeatNumber, HeatSuffix, Operation,
COUNT(Operation) AS [Pieces Out of Tolerance]
FROM Alerts
WHERE (Mill = 3)
AND (DateEntered BETWEEN @DateFrom AND @DateTo)
GROUP BY OrderNumber, OrderRelease, HeatNumber, HeatSuffix, Operation
, 120
指定ODBC日期时间格式,无论语言环境如何,它都是常量。
答案 1 :(得分:3)
SELECT OrderNumber
, OrderRelease
, HeatNumber
, HeatSuffix
, Operation
, COUNT(Operation) AS [Pieces Out of Tolerance]
FROM Alerts
WHERE (Mill = 3)
AND (datediff(dd,DateEntered,getdate()) = 0 AND Datepart(hh,DateEntered) BETWEEN '08' AND '16')
GROUP BY OrderNumber, OrderRelease, HeatNumber, HeatSuffix, Operation
答案 2 :(得分:0)
由于您使用的是SQL Server 2008,因此可以将CAST作为日期或时间。要在08:00获取当前日期,您将使用:
(CAST(CAST(getdate() AS DATE) AS DATETIME) + CAST('08:00' AS TIME))
要在16:00获取当前日期:
(CAST(CAST(getdate() AS DATE) AS DATETIME) + CAST('16:00' AS TIME)))
将此信息放入您的查询中:
SELECT OrderNumber
, OrderRelease
, HeatNumber
, HeatSuffix
, Operation
, COUNT(Operation) AS [Pieces Out of Tolerance]
FROM Alerts
WHERE (Mill = 3)
AND (DateEntered
BETWEEN (CAST(CAST(getdate() AS DATE) AS DATETIME) + CAST('08:00' AS TIME))
AND (CAST(CAST(getdate() AS DATE) AS DATETIME) + CAST('16:00' AS TIME)))
GROUP BY OrderNumber, OrderRelease, HeatNumber, HeatSuffix, Operation
答案 3 :(得分:0)
SELECT OrderNumber
, OrderRelease
, HeatNumber
, HeatSuffix
, Operation
, COUNT(Operation) AS [Pieces Out of Tolerance]
FROM Alerts
WHERE (Mill = 3)
AND (DateEntered BETWEEN DATEADD(hour, 8, CONVERT(datetime,CONVERT(date,getdate()))) AND DATEADD(hour, 18, CONVERT(datetime,CONVERT(date,getdate()))))
GROUP BY OrderNumber, OrderRelease, HeatNumber, HeatSuffix, Operation
答案 4 :(得分:0)
这可能适合你
DateEntered BETWEEN dateadd(hour, 8, cast(cast(getdate() as date) as datetime)) AND
dateadd(hour, 16, cast(cast(getdate() as date) as datetime))
但是(如您的查询所做的那样)会包含时间为16:00:00.000'
的行,但不包含时间为16:00:00.003'
的行。
如果您打算在17:00之前包含所有行,请改用它。
DateEntered >= dateadd(hour, 8, cast(cast(getdate() as date) as datetime)) AND
DateEntered < dateadd(hour, 17, cast(cast(getdate() as date) as datetime))