5

私は2つのテーブルを持っています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

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

123顧客のレコードが次のようにtable Aグループ化されるように、データを照合したいと思います。

Customer_ID  Product  Date Of Sale  Pay Meth 1  Pay Meth 2  QTY
-----------  -------  ------------  ----------  ----------  ---
        123  AB       1/1/2012             111         222    2

その右側には、 からの次のレコードが表示されますtable B

Customer_ID  Product  Date Of Sale  Pay Meth 1  Pay Meth 2  QTY
-----------  -------  ------------  ----------  ----------  ---
        123  AB       1/1/2012             111         222    2

また (常にまたあります) 3 番目のレコードtable Aをそのレコードの右側に表示したいと思いtable Bます (customer ) の 2 番目のレコードは、同じを456持っているためです。Customer_IDProductDate 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
4

2 に答える 2

5

各テーブルでサブクエリを実行して、各顧客の合計数量を取得し、その結果を顧客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
于 2012-08-02T18:51:52.180 に答える
1

探しているのは SQL JOIN コマンドです: http://www.tizag.com/sqlTutorial/sqljoin.php

一致させたい列がある行に対してのみ、2 つのテーブルを結合する必要があります。したがって、customer_id に基づいて 2 つのテーブルのレコードを一致させようとしている場合、SQL コードは次のようになります。

SELECT *
FROM A
JOIN B
ON A.Customer_ID = B.Customer_ID

これらの 2 つのレコードの ID、製品、および販売日が同じであると言う意味がよくわかりませんが、ID (456) だけが共通しているようです。

于 2012-08-02T18:33:23.830 に答える