我有一个查询在核心工作时间(7:30-16:30)之间循环。 该查询返回每个组直到日期的最新预订,但我似乎无法弄清楚确保最新返回的信息是截至循环时间
的条件。即今天的07:30,无论记录记录的日期如何,F01-F03组的最新预订都是... 。
此刻我的查询如下:
DECLARE @ALLBOOKINGS TABLE (BOOKING_GRP NVARCHAR(3), BOOKING_DATE DATETIME)
DECLARE @MAX_BACKDATE DATE = dateadd(DAY,datediff(DAY,0,getdate())-5,0),
@CURRENT_TIME TIME(0) = GETDATE(),
@START_TIME TIME(0) = '07:30:00';
BEGIN
INSERT INTO @ALLBOOKINGS
SELECT BOOKING_GRP, BOOKING_DATE
FROM TABLE1
WHERE BOOKING_DATE >= @MAX_BACKDATE
END
WHILE (@START_TIME <= @CURRENT_TIME)
BEGIN
SELECT *
FROM @ALLBOOKINGS AS T1
WHERE BOOKING_DATE = (SELECT MAX(BOOKING_DATE) FROM @ALLBOOKINGS WHERE BOOKING_GRP = T1.BOOKING_GRP)
--AND
--cast(BOOKING_DATE as time(0)) > @START_TIME AND cast(BOOKING_DATE as time(0)) < @CURRENT_TIME <<<<<<<<<<<<<<<<< this does not work, only returns max till now
SET @START_TIME = DATEADD(MINUTE,10,@START_TIME) END
表格:
+-------+-----------+-----------+-------------+-----------+-------------+
| BOOKING_GRP | BOOKING_DATE | @START_TIME |
+-------+-----------+-----------+-------------+-----------+-------------+
| F01 | 2018-12-10 11:48:50.363 | 07:30:00 |
| F02 | 2018-12-10 11:22:06.367 | 07:30:00 |
| F03 | 2018-12-10 11:21:14.240 | 07:30:00 |
+-------+-----------+-----------+-------------+-----------+-------------+
FAKE DATA - CURRENT RESULT
+-------+-----------+-----------+-------------+-----------+-------------+
| BOOKING_GRP | BOOKING_DATE | @START_TIME |
+-------+-----------+-----------+-------------+-----------+-------------+
| F01 | 2018-12-07 10:34:50.363 | 07:30:00 |
| F02 | 2018-12-10 12:32:06.367 | 07:30:00 |
| F03 | 2018-12-06 11:37:14.240 | 07:30:00 |
+-------+-----------+-----------+-------------+-----------+-------------+
预期结果-在最近5天之内,截至今天07:30,每组最近的预订量
答案 0 :(得分:0)
我不确定我是否完全理解这个问题,但是您可以尝试以下查询:
SELECT Booking_Group, MAX (Booking_Date) AS MaxDate
FROM SomeTable AS ST
WHERE Booking_Date BETWEEN DATEADD (MINUTE, 30, DATEADD (HH, 7, CAST (CAST (GETDATE() AS DATE) AS DATETIME)) ) AND GETDATE()
GROUP BY Booking_Group
答案 1 :(得分:0)
没有循环的理由。
declare @start datetime = '20180101'
,@end datetime = getdate()
select BOOKING_GRP,max(BOOKING_DATE) as LATEST_BOOKING_DATE
from Table1
where BOOKING_DATE between @start and @end
group by BOOKING_GRP
答案 2 :(得分:0)
已通过在while条件中添加DATE
来解决
DECLARE @STARTTIME dateTIME = dateadd(day, datediff(day, 0, getdate()), 0) + '07:30',
@CURRENTTIME DATETIME= GETDATE()
WHILE (@START_TIME <= @CURRENT_TIME)
BEGIN
SELECT *
FROM @ALLBOOKINGS AS T1
WHERE BOOKING_DATE = (SELECT MAX(BOOKING_DATE) FROM @ALLBOOKINGS WHERE BOOKING_GRP = T1.BOOKING_GRP
AND DATE_BOOKED < @STARTTIME
)
SET @START_TIME = DATEADD(MINUTE,10,@START_TIME) END