简体   繁体   English

db2联合,如果为null,则返回零

[英]db2 union, return zero if null

This unioned query works perfectly but there are some instances where there are no records for one of the three conditions. 此联合查询工作完美,但是在某些情况下,这三个条件之一没有记录。

All I would like to do is make it so that this at least returns a value of '0' if no records are found. 我要做的就是使它至少在找不到记录的情况下至少返回值“ 0”。

In other words, if nothing is found for PRIOR, instead of returning 换句话说,如果没有找到PRIOR,则返回

123 | Current | 1
123 | Full    | 2

I would get 我会得到

123 | PRIOR   | 0
123 | Current | 1
123 | Full    | 2

QUERY: 查询:

select ID, 'PRIOR' as Range, count(*) as count
    from table1
where ID = 123
AND date between '2017-01-01' and '2017-04-13'
group by ID
union all
select ID, 'CURRENT' as Range, count(*) as count
    from table1
where ID = 123
AND date between '2018-01-01' and '2018-04-13'
group by ID
union ALL
select ID, 'FULL' as Range, count(*) as count
    from table1
where ID = 123
AND date between '2017-01-01' and '2017-12-31'
group by ID;

You may rephrase your query to use conditional aggregation with no WHERE clause: 您可以重新定义查询以使用不带WHERE子句的条件聚合:

SELECT
    ID, 'PRIOR' AS Range,
    COUNT(CASE WHEN date BETWEEN '2017-01-01' AND '2017-04-13' AND ID = 123
               THEN 1 END) AS count
FROM table1
UNION ALL
SELECT
    ID, 'CURRENT' AS Range,
    COUNT(CASE WHEN date BETWEEN '2018-01-01' AND '2018-04-13' AND ID = 123
               THEN 1 END) AS count
FROM table1
UNION ALL
SELECT
    ID, 'FULL' AS Range,
    COUNT(CASE WHEN date BETWEEN '2017-01-01' AND '2017-12-31' AND ID = 123
               THEN 1 END) AS count
FROM table1;

The reason the above version should get around your problem is that it guarantees that a count report will happen for each subquery in the union, as each subquery covers the entire table. 上面的版本应该解决您的问题的原因是,它保证了联合中的每个子查询都会生成计数报告,因为每个子查询都覆盖了整个表。 The only requirement now is that table1 exists. 现在唯一的要求是table1存在。 In your original version, there would need to be at least one record with an ID of 123 , otherwise no records would be returned. 在您的原始版本中,至少需要有一条ID123记录,否则将不返回任何记录。

How about putting the values in a single row? 如何将值放在一行中?

select ID,
       sum(case when date between '2017-01-01' and '2017-04-13' then 1 else 0 end) as prior,
       sum(case when date between '2018-01-01' and '2018-04-13' then 1 else 0 end) as current,
       sum(case when date between '2017-01-01' and '2017-12-31' then 1 else 0 end) as full
from table1
where ID = 123
group by ID;

Personally, I would find the data on a single row easier to work with. 就个人而言,我会发现单行中的数据更易于使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM