我在SQL语句中遇到SUM问题。我使用的是MSSQL 2014
版本和Management Studio版本12.0.2000.8。
我试图根据他们的比例贡献和总收入的60%从表中获得每个人的股息。 每当我使用SUM(TotalShares)时,我都会让所有股东拥有相同的股息(总股息),如图所示
SELECT Names, MemGrpID, GtotalIncome, TotalShares, (GTotalIncome*0.6)*
((TotalShares)/SUM(TotalShares)) AS Dividends FROM tblDivedends GROUP BY
Names, MemGrpID, GTotalIncome, TotalShares
当我执行上述操作时,我只能使用相同的股息(总股息)获得每个名称,这是错误的。
**Names MemGrpID GTotalIncome TotalShares Dividends**
*Kevin Onyango Otieno 8484 30260.97 8000 18456.582000
*Paul Anam Otieno 6060 30260.97 5000 18456.582000
*Simon Kimani 8526 30260.97 1000 18456.582000
但是,如果只是直接或手动输入TotalShares的数字(即14000),我得到正确的分配。
SELECT Names, MemGrpID, GtotalIncome, TotalShares, (GTotalIncome*0.6)*
((TotalShares)/SUM(14000.00)) AS Dividends FROM tblDivedends GROUP BY
Names, MemGrpID, GTotalIncome, TotalShares
Names MemGrpID GTotalIncome TotalShares Dividends
*Kevin Onyango Otieno 8484 30260.97 8000 10375.179339
*Paul Anam Otieno 6060 30260.97 5000 6484.478009
*Simon Kimani 8526 30260.97 1000 1296.888339
BTW如果我
SELECT SUM(TotalShares) As TotS from tblDivedends
我得到正确的结果为14000.00。
答案 0 :(得分:0)
将总数直接添加为子查询,如果它是同一个查询,则GROUP BY生效,结果会出错。
SELECT Names, MemGrpID, GtotalIncome, TotalShares, (GTotalIncome*0.6)*
((TotalShares)/SELECT SUM(TotalShares) from tblDivedends) AS Dividends FROM tblDivedends GROUP BY
Names, MemGrpID, GTotalIncome, TotalShares
答案 1 :(得分:0)
另一种方法是参与:
SELECT Names, MemGrpID, GtotalIncome, TotalShares, (GTotalIncome*0.6)*
((TotalShares)/SUM(TotalShares) over(partition by 1)) AS Dividends FROM tblDivedends GROUP BY
Names, MemGrpID, GTotalIncome, TotalShares