我有一张表,我需要按照account_name和deal_id = X的产品的四分之一创建总销售额。
然后,我希望获得上一季度最大百分比涨幅前10名。
我一直在创建临时表,但表的大小约为1G,性能不是我们想要的。我们可以创建另一个汇总表,但在此之前我想看看是否有人建议首先使用此表。
account_name product_title type period deal_id total_amount
Account1 product1 Type A 2002_Q4 9100 146.54
Account1 product1 Type B 2002_Q4 9100 34.32
Account1 product1 Type C 2002_Q4 9100 0.02
Account1 product2 Type A 2002_Q4 9100 14.45
Account1 product2 Type B 2002_Q4 9100 3.58
Account1 product1 Type A 2002_Q3 9100 68.23
Account1 product1 Type B 2002_Q3 9100 12.56
Account1 product1 Type C 2002_Q3 9100 75.21
Account1 product2 Type A 2002_Q3 9100 5.68
Account1 product2 Type B 2002_Q3 9100 3.2
product1 180.88 2002_Q4 16%
product2 18.03 2002_Q4 103%
product1 156 2002_Q3
product2 8.88 2002_Q3
好的,我添加了新数据,并列出了上一季度所列增加的结果。
答案 0 :(得分:1)
以下是使用固定四分位数的一种方法:
select d.product_title, ((
select sum(d1.total_amount)
from deals d1
where d1.account_name = 'Account1'
and d1.deal_id = d.deal_id
and d1.product_title = d.product_title
and d1.period = '2002_Q4'
) - sum(d.total_amount)) / sum(d.total_amount) * 100
as diff
from deals d
where d.account_name = 'Account1'
and d.deal_id = 9100
and d.period = '2002_Q3'
group by d.product_title
order by diff desc
limit 10
http://sqlfiddle.com/#!9/65bd95/26
这是另一个 - 加入两个子查询:
select
q3.product_title,
100 * (q4.total - q3.total) / q3.total as diff
from (
select d.product_title, sum(d.total_amount) as total
from deals d
where d.account_name = 'Account1'
and d.deal_id = 9100
and d.period = '2002_Q3'
group by d.product_title
) q3
join (
select d.product_title, sum(d.total_amount) as total
from deals d
where d.account_name = 'Account1'
and d.deal_id = 9100
and d.period = '2002_Q4'
group by d.product_title
) q4 using (product_title)
order by diff desc
limit 10
http://sqlfiddle.com/#!9/65bd95/9
有用的索引是(account_name, period, deal_id, product_title, total_amount)
。前三列可以按任何顺序排列。最后一个是可选的,但是它可以覆盖"覆盖"索引。