在下面的代码中,如果结束日期的小时等于0,我希望Select Top的第一行看起来像这样。
SELECT TOP ( ABS(DATEDIFF(HOUR, A.startdatetime, A.enddatetime) + 1))
但是,如果结束日期的小时数不等于0,我希望它看起来像这样。
SELECT TOP ( ABS(DATEDIFF(HOUR, A.startdatetime, A.enddatetime)))
但是,我正在努力确定如何将案例声明并入其中,因为它需要放在交叉申请中。
--Create my temporary table
SELECT * into #Temporary
FROM dbo.Census
WHERE year(startdatetime) >= 2018
ORDER BY startdatetime, pt_id
--Use the Cross Apply to split out every day into every hour
SELECT
Date = CAST(D AS DATE)
,Hour = DATEPART(HOUR, D)
,A.pt_id
,cendate
,A.[locationid]
,A.[room-bed]
,startdatetime
,enddatetime
,minutes
,MyStartMinutes = 0
,MyEndMinutes = 0
INTO #Temporary2
FROM #Temporary A
CROSS APPLY
(
SELECT TOP ( ABS(DATEDIFF(HOUR, A.startdatetime, A.enddatetime) + 1))
D = DATEADD(HOUR, -1 + ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL )), A.startdatetime)
FROM master..spt_values n1
,master..spt_values n2
) B
Sample Data
Date pt_id cendate loc startdate enddate minutes
10/9/2018 100 10/2/2018 A 10/1/2018 22:00 10/2/2018 0:35 155
10/10/2018 100 10/2/2018 B 10/2/2018 0:35 10/2/2018 23:00 1345
It should result in:
Date Hour loc pt_id (Start Time) (End Time)
10/9/2018 22 A 100 10/9/2018 22:00 10/9/2018 23:00
10/9/2018 23 A 100 10/9/2018 23:00 10/10/2018 0:00
10/10/2018 0 A 100 10/10/2018 0:00 10/10/2018 0:35
10/10/2018 0 B 100 10/10/2018 0:35 10/10/2018 1:00
答案 0 :(得分:0)
替换此:
SELECT TOP ( ABS(DATEDIFF(HOUR, A.startdatetime, A.enddatetime) + 1))
与此:
SELECT TOP (ABS(DATEDIFF(HOUR, A.startdatetime, A.enddatetime) + (CASE WHEN DATEPART(HOUR, A.enddatetime) = 0 THEN 1 ELSE 0 END)))