如何选择日期范围内的记录?例如,假设开始日期是9/1/2019,结束日期是9/5/2019。然后我要选择虚拟记录,如下所示:
我的问题是没有保存记录的表。
Date |Some Data
--------|---------
9/1/2019|Some Data
9/2/2019|Some Data
9/3/2019|Some Data
9/4/2019|Some Data
9/5/2019|Some Data
答案 0 :(得分:1)
您可以使用递归CTE尝试以下选项-
DECLARE @start_date DATE= '2019-09-01', @end_date DATE= '2019-09-05';
WITH cte
AS
(
SELECT @start_date AS date_, 'Some Data' AS Val
UNION ALL
SELECT CAST(DATEADD(day, 1, date_) AS DATE), 'Some Data' AS Val
FROM cte
WHERE date_ < @end_date
)
SELECT *
FROM cte OPTION(MAXRECURSION 0);
输出为-
date_ Val
2019-09-01 Some Data
2019-09-02 Some Data
2019-09-03 Some Data
2019-09-04 Some Data
2019-09-05 Some Data
答案 1 :(得分:0)
以下查询与您描述的内容完全相同:
SELECT Date, [Some Data]
FROM yourTable
WHERE Date BETWEEN '20190901' AND '20190905';
但是,这当然是假设这样的表确实存在,并且您维护了日期列。
答案 2 :(得分:0)
我通过使用存储过程找到了这个问题的答案:
答案 3 :(得分:0)
递归CTE的一种替代方法是使用计数/数字表
DECLARE @start_date DATE= '2019-09-01', @end_date DATE= '2019-09-05';
; with NUMBERS AS ( -- replace with proper numbers/tally table
select d.number from (values (0), (1), (2), (3), (4), (5), (6), (7), (8)) as d(number)
)
SELECT DATEADD(DAY, number, @start_date) as [Date]
, 'Some Data' as [Some Data]
FROM NUMBERS
WHERE NUMBER >= 0 AND NUMBER <= DATEDIFF(day, @start_date, @end_date)