我试图在SQL中获得两列的百分比,但是由于某种原因,方程的除法部分没有发生?
我对此很陌生,但很高兴学习。谢谢您的帮助!
SELECT
Jaar,
SUM(Bedrag) AS 'Totaal te innen contributie',
(SELECT SUM(Bedrag)
FROM Betaling
WHERE Jaar = Contributie.Jaar) AS 'Totaal geïnde contributie',
CAST((SUM(Bedrag) / (SELECT SUM(Bedrag)
FROM Betaling
WHERE Jaar = Contributie.Jaar) * 100) AS numeric(7,2)) AS 'percentage beta'
FROM
Contributie
GROUP BY
Jaar
答案 0 :(得分:2)
我们可以使用联接来实现:
SELECT
c.Jaar,
SUM(c.Bedrag) AS 'Totaal te innen contributie',
b.bedrag_sum AS 'Totaal geïnde contributie',
100.0 * SUM(c.Bedrag) / b.bedrag_sum AS 'percentage beta'
FROM Contributie c
LEFT JOIN
(
SELECT Jaar, SUM(Bedrag) AS bedrag_sum
FROM Betaling
GROUP BY Jaar
) b
ON c.Jaar = b.Jaar
GROUP BY
c.Jaar;
别名为b
的子查询将替换您在select子句中拥有的相关子查询。