当两个表出现在第一个表中而不是在第二个表中时,如何连接表并从中获取结果,反之亦然

时间:2014-04-29 07:08:27

标签: sql sql-server join

我想要在SQL Server 2012中加入2个表。连接必须位于tblA.customer_id列到tblB.customer,加入2表tblA和tblB之后,我想要tblA.date_of_revevenue等于tblB.revenue_date,然后添加tblA.revenue + tblB.revenue_amount并将它们显示在1行中,但如果tblA.date_of_revevenue与tblB.revenue_date不同,则在结果表Tbl_Total_Revenue中的2个不同的行中显示它们。

我已经超过10个小时试图加入使用全外连接,但它不起作用。我需要你的帮助,伙计们。

这是我拥有的样本表和我正在寻找的是结果表,如下所示。 谢谢

tbl_A

* Customer_id | Date_of_revenue |收入

  • C1 | 201201 | 100
  • C2 | 201203 | 120.20
  • C4 | 201304 | 150
  • C5 | 201401 | 70

tbl_B

*客户| Revenue_date | Revenue_amount

  • C1 | 201201 | 50
  • C2 | 201203 | 200
  • C3 | 201403 | 250
  • C5 | 201310 | 50
  • C4 | 201401 | 20

我想要的结果表

Tbl_Total_Revenue

* Customer_id | Revenue_date | TOTAL_REVENUE

  • C1 | 201201 | 150
  • C2 | 201203 | 320.20
  • C3 | 201403 | 250
  • C4 | 201304 | 150
  • C4 | 201401 | 20
  • C5 | 201401 | 70

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT Customer_id, Date_of_revenue, SUM(Revenue)
FROM
    (
        (SELECT Customer_id, Date_of_revenue, Revenue FROM tbl_A)
        UNION
        (SELECT Customer Customer_id, Revenue_date Date_of_revenue, Revenue_amount Revenue FROM tbl_B)
    )
GROUP BY Customer_id, Date_of_revenue

答案 1 :(得分:0)

样本数据(或预期结果)中存在错误,C5应该有两行:

select isnull(a.Customer_id, b.Customer), isnull(a.Date_of_revenue, b.Revenue_date),
    sum(isnull(a.Revenue,0)+isnull(b.Revenue_amount,0)) as Total_revenue
from tbl_A a
full join tbl_B b on a.Customer_id = b.Customer
and a.Date_of_revenue = b.Revenue_date
group by isnull(a.Customer_id, b.Customer), isnull(a.Date_of_revenue, b.Revenue_date)
order by isnull(a.Customer_id, b.Customer), isnull(a.Date_of_revenue, b.Revenue_date)