db2 union,如果为null则返回零

时间:2018-04-13 14:42:17

标签: sql db2

这个联合查询工作正常,但有些情况下三个条件之一没有记录。

我想做的就是让它至少在没有找到记录的情况下返回值'0'。

换句话说,如果没有找到PRIOR的任何内容,而不是返回

123 | Current | 1
123 | Full    | 2

我会得到

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;

2 个答案:

答案 0 :(得分:1)

您可以将查询重新定义为使用不带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;

上述版本应该解决您的问题的原因是它保证了联合中每个子查询都会发生计数报告,因为每个子查询都覆盖整个表。现在唯一的要求是table1存在。在原始版本中,至少需要一条ID 123的记录,否则不会返回任何记录。

答案 1 :(得分:1)

如何将值放在一行中?

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;

就个人而言,我会发现单行上的数据更容易使用。