基于SUM的SQL'WHERE'限制

时间:2016-02-24 19:35:28

标签: mysql aggregate-functions

我通过使用

对历史交易求和来计算当前头寸
SELECT pairID, instrumentID, Sum(sharesTraded)
FROM cef_schema.pairadj_table 
GROUP BY pairID, instrumentID ORDER BY pairID;

这样可以正常工作,但即使当前位置(sharesTraded之和)为0,也会为每对产生响应。我宁愿忽略这些,但如果我尝试用WHERE Sum(sharesTraded)!=0限制SELECT,则会出错

有没有办法将结果限制为非零和?

2 个答案:

答案 0 :(得分:4)

您可以使用HAVING

SELECT pairID, instrumentID, Sum(sharesTraded) as sharesTradedSum
FROM cef_schema.pairadj_table 
GROUP BY pairID, instrumentID 
HAVING sharesTradedSum > 0
ORDER BY pairID

答案 1 :(得分:2)

需要HAVING使用GROUP BY代替WHERE