【问题标题】:DB2 SQL select count over union of multiple tablesDB2 SQL 选择计数超过多个表的联合
【发布时间】:2015-09-07 21:44:31
【问题描述】:

我需要返回多个表中特定条件的记录数

select count(*) c from table1
where exists (select * from crosstable where crosstable.refid = table1.id)
and crosstable.year = 2014
union
select count(*) c from table2
where exists (select * from crosstable where crosstable.refid = table2.id)
and crosstable.year = 2014
union
select count(*) c from table3
where exists (select * from crosstable where crosstable.refid = table3.id)
and crosstable.year = 2014

这会从表中返回一个唯一整数值​​的结果集。

所以如果 table1 返回 '1' 并且 table2 和 table3 返回 '5' 我得到 '1', '5' 而不是 '1', '5', '5'。

而且它似乎并没有发挥作用

select sum(c) from (previous query))

我尝试使用 sysdummy 表,但我的语法不正确,我找不到任何好的例子来解决这个问题。可能是我完全错误地处理它..

最后我需要我的结果是 1 个单个数字,这是联合部分中每个子查询的计数

【问题讨论】:

  • 您希望返回什么结果集?所有三个计数的总和?
  • 是的,更新我的问题:)

标签: sql db2


【解决方案1】:

您的查询

select sum(c) from (previous query)

很好——差不多。 DB2 期望子查询有别名,所以试试:

select sum(c) from (previous query) x

顺便说一句,您的union 几乎肯定需要是union allunion 消除重复。

【讨论】:

    【解决方案2】:

    请在下面试试

    with temp as (
        select count(*) c from table1
        where exists (select * from crosstable where crosstable.refid = table1.id)
        and crosstable.year = 2014
        union all
        select count(*) c from table2
        where exists (select * from crosstable where crosstable.refid = table2.id)
        and crosstable.year = 2014
        union all
        select count(*) c from table3
        where exists (select * from crosstable where crosstable.refid = table3.id)
        and crosstable.year = 2014
    )
    select sum(c) as final_count from temp;
    

    【讨论】:

    • 你应该添加一个关于你修复了什么的简短说明。
    猜你喜欢
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多