我有一个名为Employee的表名。即使任何一个日子都缺失,我也希望得到所有日期。
表:
create table Employee(id int, dateCheck datetime)
insert into Employee values(1, '2016/01/01')
insert into Employee values(2, '2016/01/02')
insert into Employee values(3, '2016/01/05')
insert into Employee values(4, '2016/01/07')
E.g:
+-------------------+--------------------------+
|Name | dateCheck |
+-------------------+--------------------------+
| 1 | 2016-01-01 00:00:00.000 |
| 2 | 2016-01-02 00:00:00.000 |
| 3 | 2016-01-05 00:00:00.000 |
| 4 | 2016-01-07 00:00:00.000 |
+-------------------+--------------------------+
我需要输出如下:
+-------------------+--------------------------+
|Name | dateCheck |
+-------------------+--------------------------+
| 1 | 2016-01-01 00:00:00.000 |
| 2 | 2016-01-02 00:00:00.000 |
| 0 | 2016-01-03 00:00:00.000 |
| 0 | 2016-01-04 00:00:00.000 |
| 3 | 2016-01-05 00:00:00.000 |
| 0 | 2016-01-06 00:00:00.000 |
| 4 | 2016-01-07 00:00:00.000 |
+-------------------+--------------------------+
请帮我解决这个任务。
答案 0 :(得分:2)
尝试
;WITH dt (mindt, mxdt)
AS (SELECT Min(dateCheck),
Max(dateCheck)
FROM Employee
UNION ALL
SELECT Dateadd(day, 1, mindt),
mxdt
FROM dt
WHERE Dateadd(day, 1, mindt) <= mxdt)
SELECT isnull(em.id,0) as id,
dt.mindt
FROM dt
LEFT JOIN employees em
ON mindt = em.dateCheck
答案 1 :(得分:0)
点击here查看建议的方法。 Tally表很棒,但是,某些实现不具备性能。拥有物理日期表有时可以提供很大的帮助。