我在DB2上运行查询:
column_1 my_count
1 33
2 20
3 14
4 2
5 33
9 27
10 16
这样可以获得按column_1分组的行数。但是,问题是我需要结果集为“IN”子句中包含0计数的任何内容包含“0”行。
目前,如果6,7和8没有满足其他“WHERE”条件的行,结果将如下所示:
shared_ptr<BaseTask>
知道怎么做到这一点?谢谢!
答案 0 :(得分:2)
这是一个简单的解决方案,使用递归CTE生成1到10之间的值。一旦你有了这个系列,就把你原来的查询左连接到它,然后你就完成了设置:
WITH v (column_1) AS (
SELECT 1 FROM SYSIBM.SYSDUMMY1
UNION ALL
SELECT column_1 + 1 FROM v WHERE column_1 <= 10
)
SELECT v.column_1, COUNT("my_table".column_1) AS "my_count"
FROM v
LEFT JOIN "my_table" ON v.column_1 = "my_table".column_1
-- Note that this predicate must be part of the LEFT JOIN condition
AND another_column = '20150609'
-- Note that this predicate might no longer be needed
WHERE "my_table".column_1 IN(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
GROUP BY v.column_1;
根据您的评论,我认为column_1
值不一定是连续的。没问题,只需编写没有递归CTE的等效查询:
WITH v (column_1) AS (
SELECT 1 FROM SYSIBM.SYSDUMMY1
UNION ALL
SELECT 42 FROM SYSIBM.SYSDUMMY1
UNION ALL
SELECT 1337 FROM SYSIBM.SYSDUMMY1
)
SELECT v.column_1, COUNT("my_table".column_1) AS "my_count"
FROM v
LEFT JOIN "my_table" ON v.column_1 = "my_table".column_1
AND another_column = '20150609'
GROUP BY v.column_1;