我想要在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个小时试图加入使用全外连接,但它不起作用。我需要你的帮助,伙计们。
这是我拥有的样本表和我正在寻找的是结果表,如下所示。 谢谢
* Customer_id | Date_of_revenue |收入
*客户| Revenue_date | Revenue_amount
我想要的结果表
* Customer_id | Revenue_date | TOTAL_REVENUE
答案 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)