[英]SQL Compare and Unity table
I have 2 table, i get problem when unity they all tell that我有 2 张桌子,当他们都告诉我时,我遇到了问题
Table 1表格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
Table 2表 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
How can I get result like this:我怎样才能得到这样的结果:
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
Please advice, thankyou!请指教,谢谢!
Below Query will help you.下面的查询将为您提供帮助。
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
Other than the UNION
already shown it's possible to JOIN
the two table, in this case having different customer in the two table a FULL JOIN
除了已经显示的
UNION
之外,还可以JOIN
两个表,在这种情况下,两个表中的不同客户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])
On a side note if you have vertical partition it'l be a lot better if you create a key to join the partition that is shorter, for example you can divide the key section and add a fake ID to relate to the other partition, something like附带说明一下,如果您有垂直分区,那么如果您创建一个键来加入较短的分区,则会好得多,例如,您可以划分键部分并添加一个假 ID 以与其他分区相关联,某事喜欢
ID | Customer | Buyer | Usage | Item Code | Item Name
ID | Month1 | Month2
ID | Month3 | Month4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.