2

如何使用递归 CTE 从 00 小时到 23 小时获得一天的小时数?

它给出了 00 到 24 小时,但我需要在我的结果集中排除 24 小时,或者换句话说,我最多只需要 00 到 23 小时

我的代码:

DECLARE @calenderDate DATETIME2(0) = '2019-05-16 05:00:00'
DECLARE @hr1Week int = 0

;with numcte AS  
       (  
         SELECT 0 [num]  
         UNION all  
         SELECT [num] + 1 FROM numcte WHERE [num] < (Select  datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)))
       )        

select * from numcte

它给出了 00 到 24 小时,但我需要在我的结果集中排除 24 小时,或者换句话说,我最多只需要 00 到 23 小时

实际结果:

num
----
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

预期结果:

num
---
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
4

1 回答 1

2

而不是
Select datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)),将其更改为
Select datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)) - 1
只会返回最多 23 小时

DECLARE @calenderDate DATETIME2(0) = '2019-05-16 05:00:00'
DECLARE @hr1Week int = 0

;with numcte AS  
(  
     SELECT 0 [num]  
     UNION all  
     SELECT [num] + 1 FROM numcte WHERE [num] < 
      (SEELCT datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)) -1)
)        

SELECT * FROM numcte

db<>fiddle 上的演示

于 2019-05-15T05:48:09.900 回答