2017-08-03 15 views
0

私はその後、最大%のトップ10リストをしたい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を意味しました。私はwhere節で渡される変数としてXを使用していました。 –

+0

四半期あたりの合計金額は、その異なるタイプを構成する合計金額の合計となります。タイプ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

は別のものである - 2つのサブクエリ接合:親切インデックスがあろう

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)。最初の3つの列の順序は任意です。最後のものはオプションですが、 "カバリング"インデックスになります。

+0

良い仕事。これがどのように動的であるかはわかりません。 '2002_Q2'、' 2002_Q3'、 '2002_Q4'の結果は、乱雑な正規表現なしで得られます。私はこれがOPのための最良の選択肢だと思う。 – TheDetective

+0

これは機能しました。パフォーマンスの観点から、結合のない最初のものは指数関数的に高速でした。私はちょうど質問を殺した分に比べて9秒。それは私がテーブルに正しいインデックスを入れた後です。ありがとう!! –

+0

@SeanPeace最初のサブクエリで 'd1.account_name = 'Account1''が見つからないという不具合を修正しました。また、実際に "正しい"インデックスがあるかどうかを確認してください。 –

関連する問題