我有两个查询(示例版本) -
查询A:
select
col1 as COL1,
col2 as COL2,
sum(col3) as COL3
from table1 join table11 ..
group by col1, col2;
查询B:
select
col1 as COL1,
col2 as COL2,
count(col3) as COL3
from table2
group by col1, col2;
我想加入他们两个并输出如下所示。试过这个
select A.COL1, A.COL2, greatest(A.COL3, B.COL3)
from (query A) A
UNION (query B) B
但收到错误
SQL0104N An unexpected token "END-OF-STATEMENT" was found following "col2) B". Expected tokens may include: "JOIN <joined_table>". SQLSTATE=42601
两个查询单独运行正常,但如果像上面那样使用UNION进行组合,则会出错。
有没有更好的方法来实现这一目标?
答案 0 :(得分:0)
看起来您需要加入,而不是联盟:
select A.COL1, A.COL2, greatest(A.COL3, B.COL3)
from (query A) A
join (query B) B on A.COL1 = B.COL1 and A.COL2 = B.COL2
根据您的需要,您可能需要left join
,right join
或full outer join
而不是内部join
。
答案 1 :(得分:0)
with A as
(
select
col1 as COL1,
col2 as COL2,
sum(col3) as COL3
from table1 join table11 ..
group by col1, col2
),
B as
(
select
col1 as COL1,
col2 as COL2,
count(col3) as COL3
from table2
group by col1, col2
)
select ifnull(A.COL1, B.COL1) as COL1, ifnull(A.COL2, B.COL2) as COL2,
greatest(ifnull(A.COL3, 0), ifnull(B.COL3, 0)) as great
from A full outer join B on A.COL1 = B.COL1 and A.COL2 = B.COL2