2017-08-03 56 views
0

我有一個表,我需要通過產品的季度創造的總銷售額在ACCOUNT_NAME和DEAL_ID = X.SQL季度總與%的增幅排名前十

我再想最大一%榜前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

究竟是什麼「X」? – TheDetective

+0

對不起。 X表示account_name = Account1和deal_id = 9100.我只是使用X,因爲那些變量將在where子句中傳遞。 –

+0

每個季度的總金額將是包含不同類型的product1總計的總和。類型A +類型B +類型C =總數。 (Account1,product1,9100,2002_Q4,46.54 + 34.32 + .02 = 80.88) –

回答

1

這裏是固定quartals單程:

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)。前三列可以按任意順序排列。最後一個是可選的,但是使其成爲「覆蓋」索引。

+0

好的工作。我不明白這可能是動態的,例如獲得'2002_Q2','2002_Q3'和'2002_Q4'的結果沒有一些凌亂的正則表達式。我認爲這將是OP的最佳選擇。 – TheDetective

+0

這工作。從性能角度來看,沒有連接的第一個速度指數更快。 9秒相比,我剛剛殺了查詢一分鐘。那是在我把正確的索引放在表格上之後。謝謝!! –

+0

@SeanPeace剛在第一個子查詢中修復缺少'd1.account_name ='Account1''。同時檢查你是否真的有「正確的」索引。 –