是否有一种简单的方法可以在联合中跳过NULL行? 我在DB2上。
示例:
SELECT 'FIRST', sum(value) FROM SYSIBM.SYSDUMMY1
UNION
SELECT 'SECOND', sum(value) FROM SYSIBM.SYSDUMMY1
UNION
SELECT 'THIRD', sum(value) FROM SYSIBM.SYSDUMMY1
结果:
1---------|2-----
FIRST 1
SECOND NULL/0
THIRD 3
因此,如果其中一个联合有0或NULL,则应跳过它:
估算的示例结果:
1---------|2-----
FIRST 1
THIRD 3
答案 0 :(得分:4)
使用子查询。我还建议union all
:
SELECT col, val
FROM (SELECT 'FIRST' as col, sum(value) as val FROM SYSIBM.SYSDUMMY1
UNION ALL
SELECT 'SECOND' as col, sum(value) as val FROM SYSIBM.SYSDUMMY1
UNION ALL
SELECT 'THIRD' as col, sum(value) as val FROM SYSIBM.SYSDUMMY1
) t
WHERE val IS NOT NULL AND val > 0;
注意:
UNION
会产生删除重复项的开销。使用UNION ALL
可以避免这种开销。val IS NOT NULL
是多余的。但它明确表达了你想要的条件。答案 1 :(得分:2)
是的,您可以使用IS NOT NULL
过滤器检查HAVING
来执行此操作。
SELECT 'FIRST', sum(value)
FROM SYSIBM.SYSDUMMY1 GROUP BY 'FIRST' HAVING sum(value) IS NOT NULL
UNION
SELECT 'SECOND', sum(value)
FROM SYSIBM.SYSDUMMY1 GROUP BY 'SECOND' HAVING sum(value) IS NOT NULL
UNION
SELECT 'THIRD', sum(value)
FROM SYSIBM.SYSDUMMY1 GROUP BY 'THIRD' HAVING sum(value) IS NOT NULL
如果sum(value)
中的任何一个返回NULL
,则由于SELECT
子句,关联的GROUP BY
语句将返回零行,从而导致相应的行省略。 / p>
如果您想省略基于 a NULL
或零和的行,请像这样添加AND
连词:< / p>
SELECT 'FIRST', sum(value) FROM SYSIBM.SYSDUMMY1 GROUP BY 'FIRST' HAVING sum(value) IS NOT NULL AND NOT sum(value) = 0
UNION
SELECT 'SECOND', sum(value) FROM SYSIBM.SYSDUMMY1 GROUP BY 'SECOND' HAVING sum(value) IS NOT NULL AND NOT sum(value) = 0
UNION
SELECT 'THIRD', sum(value) FROM SYSIBM.SYSDUMMY1 GROUP BY 'THIRD' HAVING sum(value) IS NOT NULL AND NOT sum(value) = 0
此外,您可以通过将UNION
更改为UNION ALL
来提高查询的效率,因为您的最终结果中不会有重复的行。 UNION
执行重复检查,在这种情况下永远不会触发。