我有两张桌子,table A:
Customer_ID Product Date Of Sale Pay Meth 1 Pay Meth 2 QTY
----------- ------- ------------ ---------- ---------- ---
123 AB 1/1/2012 111 222 1
123 AB 1/1/2012 111 222 1
456 AC 2/1/2012 333 444 1
Run Code Online (Sandbox Code Playgroud)
并且table B:
Customer_ID Product Date Of Sale Pay Meth 1 Pay Meth 2 QTY
----------- ------- ------------ ---------- ---------- ---
123 AB 1/1/2012 111 222 2
456 AB 1/1/2012 124 111 1
Run Code Online (Sandbox Code Playgroud)
我想,这样的客户记录匹配的数据了123在table A被归纳为:
Customer_ID Product Date Of Sale Pay Meth 1 Pay Meth 2 QTY
----------- ------- ------------ ---------- ---------- ---
123 AB 1/1/2012 111 222 2
Run Code Online (Sandbox Code Playgroud)
在它的右边出现以下记录table B:
Customer_ID Product Date Of Sale Pay Meth 1 Pay Meth 2 QTY
----------- ------- ------------ ---------- ---------- ---
123 AB 1/1/2012 111 222 2
Run Code Online (Sandbox Code Playgroud)
另外(总有一个)我们想要在该记录table A的右侧显示第三条记录table B(客户456)中的第二条记录,因为它们具有相同的Customer_ID,Product并且Date of Sale
所以看起来应该是这样的
Customer_ID Product Date Of Sale Pay Meth 1 Pay Meth 2 QTY Customer_ID Product Date Of Sale Pay Meth 1 Pay Meth 2 QTY
----------- ------- ------------ ---------- ---------- --- ----------- ------- ------------ ---------- ---------- ---
123 AB 1/1/2012 111 222 1 123 AB 1/1/2012 111 222 1
456 AC 2/1/2012 333 444 1 456 AB 1/1/2012 124 111 1
Run Code Online (Sandbox Code Playgroud)
您可以在每个表上执行子查询以获取每个客户的总和数量,然后通过客户ID加入结果,例如
SELECT a.*, b.*
FROM (
Select customer_id, product, dateofsale, PayMeth1, PayMeth2, SUM(Qty) as Qty
from TableA
Group by customer_id, product, dateofsale, PayMeth1, PayMeth2
) a
JOIN (
Select customer_id, product, dateofsale, PayMeth1, PayMeth2, SUM(Qty) as Qty
from TableB
Group by customer_id, product, dateofsale, PayMeth1, PayMeth2
) b
ON a.customer_id = b.customer_id
Run Code Online (Sandbox Code Playgroud)