考虑一个销售应用程序,我们有两个表SALES和INTERNAL_SALES。
销售表: 即使交易为零,每个日期对每个销售人员也有一个条目。
id | day | sales_person | number_of_transactions 1 | 2011-08-01 | Tom | 1000 2 | 2011-08-01 | Ben | 500 3 | 2011-08-01 | Anne | 1500 4 | 2011-08-02 | Tom | 0 5 | 2011-08-02 | Ben | 800 6 | 2011-08-02 | Anne | 900 7 | 2011-08-03 | Tom | 3000 8 | 2011-08-03 | Ben | 0 9 | 2011-08-03 | Anne | 40
INTERNAL_SALES表: 此表仅记录销售人员之间实际进行的交易。
id | day | sales_person_from | sales_person_to | number_of_transactions 0 | 2011-08-01 | Tom | Ben | 10 1 | 2011-08-01 | Tom | Anne | 20 2 | 2011-08-01 | Ben | Tom | 50 3 | 2011-08-03 | Anne | Tom | 30 4 | 2011-08-03 | Anne | Tom | 30
现在问题是每个销售人员每天都要进行总交易。我这样做的方式是:
SELECT day, sales_person, sum(num_transactions) from ( SELECT day, sales_person, number_of_transactions As num_transactions FROM sales; UNION SELECT day, sales_person_from As sales_person, sum(number_of_transactions) As num_transactions FROM internal_sales GROUP BY day, sales_person_from; ) GROUP BY day, sales_person;
这太慢了,看起来很难看。我正在寻求更好的解决方案。顺便说一句,在Oracle中使用的数据库和我无法控制数据库,除了我可以对它运行查询。
答案 0 :(得分:7)
不需要聚合两次,并且union运算符通常执行隐式唯一排序,这在您的情况下也是不必要的。
SELECT day, sales_person, sum(num_transactions) from
(
SELECT day, sales_person, number_of_transactions As num_transactions FROM sales;
UNION ALL
SELECT day, sales_person_from, number_of_transactions FROM internal_sales;
)
GROUP BY day, sales_person;
删除中间聚合和唯一排序应该有所帮助。