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 将每一行链接两次。

尝试使用工会如下

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 回答