即使在SQL Server中也没有数据的情况下,如何在一个表中获取日期范围内的所有日期

时间:2018-12-10 07:05:11

标签: mysqli

我有一个表名称叫Tab1。我希望得到所有日期,即使也缺少某几天。

 +-------------------+--------------------------+
 |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  |
 +-------------------+--------------------------+
I need output like below :
 +-------------------+--------------------------+
 |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  | 

1 个答案:

答案 0 :(得分:0)

您可以使用日历表:

SELECT
    COALESCE(t2.Name, 0) AS Name,
    t1.dateCheck
FROM
(
    SELECT '2016-01-01' AS dateCheck UNION ALL
    SELECT '2016-01-02' UNION ALL
    SELECT '2016-01-03' UNION ALL
    SELECT '2016-01-04' UNION ALL
    SELECT '2016-01-05' UNION ALL
    SELECT '2016-01-06' UNION ALL
    SELECT '2016-01-07'
) t1
LEFT JOIN yourTable t2
    ON t1.dateCheck = t2.dateCheck;