表1
MONTH ACCT_NUM PRODUCT REVENUE
Jan 9994523 VEG 50.00
Jan 9994523 HOT DOG 40.00
Jan 9993644 HOT DOG 35.00
Jan 9993644 FRIES 2.00
Jan 9996984 VEG 60.00
Jan 9996427 15.00
表2
MONTH ACCT_NUM PRODUCT REVENUE
Feb 9994523 VEG 50.00
Feb 9994523 HOT DOG 40.00
Feb 9993644 HOT DOG 35.00
Feb 9993644 FRIES 2.00
Feb 9996984 VEG 60.00
Feb 9996427 15.00
预期产出
ACCT_NUM REVENUE_TOTAL
9993644 74.00
9994523 180.00
9996427 30.00
9996984 120.00
我正在尝试在两个表上执行完全连接,并通过操作在顶部执行组。我的方法有什么问题,或者下面的查询是否有更好的方法
Q1 = SELECT T1.*
FROM Table1 T1
FULL OUTER JOIN Table2 T2 ON T1.ACCT_NUM = T2.ACCT_NUM
select distinct ACCT_NUM, sum(REVENUE) as REVENUE_TOTAL from Q1 group by ACCT_NUM
答案 0 :(得分:1)
使用Union All
。
http://sqlfiddle.com/#!6/f8e69/8
Select
ACCT_NUM, sum(REVENUE) REVENUE_TOTAL
From
(
Select ACCT_NUM, REVENUE from Table1
Union All
Select ACCT_NUM, REVENUE from Table2
) A
Group By A.ACCT_NUM
更多阅读材料:)参考:What is the difference between JOIN and UNION?
UNION将查询中的行放在彼此之后,而JOIN生成一个 笛卡尔积和子集......