SELECT
business_period,
SUM(transaction.transaction_value) AS total_transaction_value,
SUM(transaction.loss_value) AS total_loss_value,
(total_transaction_value - total_loss_value) AS net_value
FROM transaction
GROUP BY business_period
以上内容不起作用,也不total_transaction_value
是total_loss_value
来自transaction
表格。有没有办法使这个查询工作?
注意:这个查询涉及5亿行,所以需要高效。
问题:
一些答案建议SUM(transaction.transaction_value) - SUM(transaction.loss_value)
已缓存并且不需要再次计算,因为其他人建议我应该作为派生表/子查询以避免重复计算。有人能指出一些可以解决意见分歧的事情吗?
我正在使用 postgres 9.3。
回答:
我想在这里引用 erwin 的评论:
I ran a quick test with 40k rows and the winner was the plain version without subquery. CTE was slowest. So I think my first assumption was wrong and the query planner understands not to calculate the sums repeatedly (makes sense, too). I have seen different results with more complex expressions in the past. The planner does get smarter with every new version