2

私は3つのテーブルを持ってA, BおりC、列があります

UserId, CompanyId, Quantity, Rate 

以下のこのクエリのような結果を返すクエリを実行したい

SELECT 
    (A.Quantity + B.Quantity + C.Quantity) AS TotalQuantity, 
    SUM(A.Quantity * A.Rate) + SUM(C.Quantity * C.Rate) AS TotalAmount, 
    TotalQuantity/TotalAmount AS Result 
FROM 
    A, B, C  
WHERE
    (A.UserId = 1 AND A.CompanyId = 1) 
    AND 
    (A.UserId = B.UserId AND A.UserId = C.UserId AND A.CompanyId = B.CompanyId 
     AND A.CompanyId = C.CpmpanyId)

このクエリを実行しようとしましたが、想定どおりに動作しません。ここで何かが欠けています。親切に私を助けてください。

Table A 

UID    CID    Quantity  Rate
1       1      90        60
1       1      100        9


Table B

UID    CID    Quantity
1       1       100
1       1       50

Table C

UID    CID    Quantity  Rate
1       1       5        5
1       1       5        5
4

2 に答える 2

3

編集した質問に基づいてクエリを変更する:

select sum(Quantity) TotalQuantity, sum(Quantity * Rate) TotalAmount, sum(Quantity) / sum(Quantity * Rate * 1.0) Result
from
(
   select UID, CID, Quantity, Rate
   from A
   union all
   select UID, CID, Quantity, 1 Rate
   from B
   union all
   select UID, CID, Quantity, Rate
   from C
) t
where
   t.UID = 1 
   and t.CID = 1

また、ここに実例があります

于 2013-06-26T20:45:21.323 に答える
-1

データの問題は、結合によって行が複製されることです。A.UID=B.UID AND A.CID=B.CID は、各行を 2 回リンクします。

次のようにユニオンを使用してみてください

SELECT SUM(t.TotalQuantity), SUM(t.TotalAmount), SUM(t.TotalQuantity)/SUM(t.TotalAmount) FROM (
    SELECT 
        CID, UID, SUM(Quantity) AS TotalQuantity, SUM(Quantity*Rate) AS TotalAmount
    FROM A 
    GROUP BY CID, UID
    UNION ALL
    SELECT 
        CID, UID, SUM(Quantity), 0
    FROM B 
    GROUP BY CID, UID
    UNION ALL
    SELECT 
        CID, UID, SUM(Quantity), SUM(Quantity*Rate)
    FROM C 
    GROUP BY CID, UID
) t
WHERE t.UID=1 AND t.CID=1

コメントで求められているように、データを会社別にグループ化するには:

SELECT t.CID, SUM(t.TotalQuantity), SUM(t.TotalAmount), SUM(t.TotalQuantity)/SUM(t.TotalAmount) FROM (
    SELECT 
        CID, UID, SUM(Quantity) AS TotalQuantity, SUM(Quantity*Rate) AS TotalAmount
    FROM A 
    GROUP BY CID, UID
    UNION ALL
    SELECT 
        CID, UID, SUM(Quantity), 0
    FROM B 
    GROUP BY CID, UID
    UNION ALL
    SELECT 
        CID, UID, SUM(Quantity), SUM(Quantity*Rate)
    FROM C 
    GROUP BY CID, UID
) t
WHERE t.UID=1
GROUP BY t.CID
于 2013-06-26T20:43:07.913 に答える