如何选择缺少的日期值

时间:2017-05-19 21:06:03

标签: sql sql-server-2008 gaps-and-islands

我目前正在尝试查看缺少日期,如果某个特定“属性”缺少过去3天的日期值:

SELECT property, business_date
    FROM my_table
        WHERE business_date BETWEEN DATEADD(DAY, -2, @business_date) AND @business_date
        AND property IN
        (
        SELECT property
            FROM my_table
                WHERE business_date BETWEEN DATEADD(DAY, -2, @business_date) AND @business_date
                    GROUP BY property
                        HAVING COUNT(property) <> 3
    )

目前显示:

0088 2017-05-16 00:00:00.000
0088 2017-05-18 00:00:00.000
0094 2017-05-17 00:00:00.000
0094 2017-05-18 00:00:00.000

我试图让它显示缺失值,而不是我拥有的值。 所以我想告诉我:

0088 2017-05-17 00:00:00.000
0094 2017-05-16 00:00:00.000

我尝试创建一个日历表:

DECLARE @calendar TABLE
(
    date DATETIME
)
INSERT INTO @calendar
SELECT DATEADD(DAY, -2, @business_date) UNION ALL
SELECT DATEADD(DAY, -1, @business_date) UNION ALL
SELECT DATEADD(DAY, 0, @business_date)

1 个答案:

答案 0 :(得分:1)

您应该cross join个不同的属性值包含日期,left join属于原始表格。

SELECT P.property,C.DATE
FROM (SELECT DISTINCT PROPERTY FROM my_table) P
CROSS JOIN @calendar C 
LEFT JOIN MY_TABLE M ON M.PROPERTY=P.PROPERTY AND M.BUSINESS_DATE=C.DATE
WHERE M.BUSINESS_DATE IS NULL