我有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
答案 0 :(得分: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
此处还有working example
答案 1 :(得分:-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