如何 select 缺少日期值
How to select missing date value
如果某个特定 "property" 缺少过去 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
我尝试创建日历 table:
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)
您应该 cross join
不同的 属性 值和日期 left join
到原始 table。
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
如果某个特定 "property" 缺少过去 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
我尝试创建日历 table:
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)
您应该 cross join
不同的 属性 值和日期 left join
到原始 table。
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