我正在尝试加入两个表,但问题是收银台表可以与销售表中的3个字段连接,如果我只使用一个字段加入两个表,我不想错过任何记录。我只想获得与收银台一样多的行。我希望这是有道理的。这是我想要做的一个例子。
SELECT cashiers.cashierId,cashiers.name,cashiers.age,
(SELECT
(SELECT SUM(amount) * .20 FROM sales WHERE cashierId1 = cashiers.cashierId) +
(SELECT SUM(amount) * .30 FROM sales WHERE cashierId2 = cashiers.cashierId) +
(SELECT SUM(amount) * .40 FROM sales WHERE cashierId3 = cashiers.cashierId)
) AS totalAmount
FROM cashiers
谢谢大家的帮助。
答案 0 :(得分:0)
也许这就是你想要做的事情:
SELECT c.cashierId, c.name, c.age,
(SELECT SUM(CASE c.cashierId WHEN s.cashierId1 THEN 0.2 * s.amount
WHEN s.cashierId2 THEN 0.3 * s.amount
WHEN s.cashierId3 THEN 0.4 * s.amount
END)
FROM sales
WHERE c.cashierId IN (s.cashierId1, s.cashierId2, s.cashierId3)
) AS totalAmount
FROM cashiers c;
答案 1 :(得分:0)
我认为戈登的答案可能不错,但我认为它也假设只有一个收银员会匹配。你可能想象的更像是这样的东西:
select
c.cashierid, min(c.name) as name, min(c.age) as age,
sum(s1.amount * 0.2) + sum(s2.amount * 0.3) + sum(s3.amount * 0.4)
from
cashiers c
left outer join sales s1 on s1.cashierid1 = c.cashierid
left outer join sales s2 on s2.cashierid2 = c.cashierid
left outer join sales s3 on s3.cashierid3 = c.cashierid
group by
c.cashierId