我有2张桌子,我们在团结时会遇到问题 告诉那个
表1
Customer | Buyer | Usage | Item Code | Item Name | Month1 | Month2
A Jirulu Bottom 111111 Item1 100 50
B Bakeyo Top 122222 Item2 100 50
D Sagero Bottom 133333 Item3 100 50
表2
Customer | Buyer | Usage | Item Code | Item Name | Month3 | Month4 |
A Jirulu Bottom 111111 Item1 100 50
C Bakeyo Top 122222 Item2 100 50
D Sagero Bottom 133333 Item3 100 50
我怎样才能得到这样的结果:
Customer | Buyer | Usage | Item Code | Item Name | Month1 | Month2| Month3 | Month4 |
A Jirulu Bottom 111111 Item1 100 50 100 50
B Bakeyo Top 122222 Item2 100 50 100 50
C Bakeyo Top 122222 Item2 0 0 100 50
D Sagero Bottom 133333 Item3 100 50 100 50
请建议,谢谢你!
答案 0 :(得分:0)
以下查询将为您提供帮助。
SELECT tab.customer,
tab.buyer,
tab.usage,
tab.usage,
tab.itemcode,
tab.itemname,
Sum(month1) AS Month1,
Sum(month2) AS Month2,
Sum(month3) AS Month3,
Sum(month4) AS Month4
FROM (SELECT customer,
buyer,
usage,
itemcode,
itemname,
month1,
month2,
0 AS month3,
0 AS month4
FROM table1
UNION ALL
SELECT customer,
buyer,
usage,
itemcode,
itemname,
0 AS month1,
0 AS month2,
month3,
month4
FROM table2) tab
GROUP BY tab.customer,
tab.buyer,
tab.usage,
tab.usage,
tab.itemcode,
tab.itemname
答案 1 :(得分:0)
除UNION
之外已经显示JOIN
这两个表的情况,在这种情况下,在两个表格中有不同的客户a FULL JOIN
SELECT Coalesce(t1.[Customer], t2.[Customer]) [Customer]
, Coalesce(t1.[Buyer], t2.[Buyer]) [Buyer]
, Coalesce(t1.[Usage], t2.[Usage]) [Usage]
, Coalesce(t1.[Item Code], t2.[Item Code]) [Item Code]
, Coalesce(t1.[Item Name], t2.[Item Name]) [Item Name]
, Coalesce([Month1], 0) [Month1]
, Coalesce([Month2], 0) [Month2]
, Coalesce([Month3], 0) [Month3]
, Coalesce([Month4], 0) [Month4]
FROM Table1 t1
FULL JOIN Table2 t2 ON t1.Customer = t2.Customer
and t1.Buyer = t2.Buyer
and t1.[usage] = t2.[usage]
and t1.[Item Code] = t2.[Item Code]
and t1.[Item Name] = t2.[Item Name]
ORDER BY Coalesce(t1.[Customer], t2.[Customer])
另一方面,如果你有垂直分区,如果你创建一个加入更短的分区的密钥,它会好很多,例如你可以划分密钥部分并添加一个假的ID来关联另一个分区,比如
ID | Customer | Buyer | Usage | Item Code | Item Name
ID | Month1 | Month2
ID | Month3 | Month4