使用where子句选择满足范围内所有日期的所有内容?

时间:2019-07-04 12:29:43

标签: sql

我有这个查询

SELECT DISTINCT fc,cohort, value
FROM test.input_test
WHERE value IS NULL AND date BETWEEN '2019-07-01' AND '2019-09-30';

我想选择在整个数据范围内(不仅在某些特定日期)值均为空的所有行。

3 个答案:

答案 0 :(得分:0)

一种方法是窗口函数:

SELECT DISTINCT fc, cohort, value
FROM (SELECT it.*,
             SUM(CASE WHEN it.value IS NULL THEN 1 ELSE 0 END) OVER () as null_cnt
      FROM test.input_test it
      WHERE it.date >= '2019-07-01' AND it.date < '2019-10-01'
     ) it
WHERE null_cnt = 0;

请注意,我更改了日期比较以避免使用BETWEENHere是一个很好的博客,解释了为什么BETWEEN是一个带有日期的坏主意。即使您不使用SQL Server,大多数情况也很重要。

答案 1 :(得分:0)

如何使用存在子句:

SELECT DISTINCT fc, cohort, value
FROM test.input_test
WHERE
    date BETWEEN '2019-07-01' AND '2019-09-30' AND
    NOT EXISTS (SELECT 1 FROM test.input_test
                WHERE date BETWEEN '2019-07-01' AND '2019-09-30' AND
                      value IS NOT NULL);

如@Gordon所述,如果要包括7月,8月和2019年9月的整个月,则应使用的日期范围是:

WHERE date >= '2019-07-01' AND date < '2019-10-01'

答案 2 :(得分:0)

您可以尝试以下方法吗:

SELECT DISTINCT IT.fc, IT.cohort, IT.value
FROM test.input_test AS IT
LEFT JOIN 
(
    SELECT fc,cohort, value 
    FROM test.input_test 
    WHERE value IS NOT NULL AND date BETWEEN '2019-07-01' AND '2019-09-30'
) AS QUERY_2 ON IT.fc = QUERY_2.fc AND IT.cohort = QUERY_2.cohort AND  IT.value = QUERY_2.value
WHERE QUERY_2.fc IS NULL