2011-07-06 15 views
1

4列(SQL 2005)のクエリを作成する必要があります。月の成長率を計算するsqlクエリ

Column1: Product 
Column2: Units sold 
Column3: Growth from previous month (in %) 
Column4: Growth from same month last year (in %) 

私のテーブルでは、年と月にカスタム整数値があります。たとえば、最新の月は146ですが、表には年(たとえば2011)の列と月(たとえば7)の列があります。

これを1つのクエリで行うことは可能ですか、または一時テーブルなどの使用を開始する必要がありますか?

ありがとうございました。

おかげで、

KS

答えて

1

KS、 場でこれを行うには、サブクエリを使用することができます。

SELECT product, this_month.units_sold, 
    (this_month.sales-last_month.sales)*100/last_month.sales, 
    (this_month.sales-last_year.sales)*100/last_year.sales 
    FROM (SELECT product, SUM(units_sold) AS units_sold, SUM(sales) AS sales 
      FROM product WHERE month = 146 GROUP BY product) AS this_month, 
     (SELECT product, SUM(units_sold) AS units_sold, SUM(sales) AS sales 
      FROM product WHERE month = 145 GROUP BY product) AS last_month, 
     (SELECT product, SUM(units_sold) AS units_sold, SUM(sales) AS sales 
      FROM product WHERE month = 134 GROUP BY product) AS this_year 
    WHERE this_month.product = last_month.product 
     AND this_month.product = last_year.product 

製品は1ヶ月で販売されていたが、別の月に、あなたがlast_month.salesまたはlast_year.salesが0の場合は特に、参加を左を行うと、null値をチェックする必要がありますない場合があります場合。

+0

これは前月の売上高が404683.00で、今月の売上高が436493.00だったときの増加率として1080.00を示します。私は答えが7.86でなければならないと確信しています。 – Perplexed

+0

SELECTステートメントの最初の行をSELECT product、this_month.units_sold、this_month.sales、last_month.sales、last_year.salesに変更して、3つの販売番号が正しいかどうか確認してください。私はちょうど私のローカルテーブルの1つに対してこれを実行し、それは正しいパーセンテージを与えているので、私はクエリが計算されている値を確認したいと思います。よろしく、ブライアン –

+0

Nvm私はそれが働いた! – Perplexed

1

は私が少し右に、結果テーブルが設けられて、テーブルの構造と推測していますか?あなたは月・ツー・前月基づいて自己結合実行する必要があります。

<growth computation here>は私が以前の数ヶ月を持っていないか月間 LEFT JOINを使用

((s1.sales - s2.sales)/s2.sales * 100), 
((s1.sales - s3.sales)/s3.sales * 100) 

のように見えます

SELECT <growth computation here> 
    FROM SALES s1 LEFT JOIN SALES s2 ON (s1.month = s2.month-1) -- last month join 
       LEFT JOIN SALES s3 ON (s1.month = s3.month - 12) -- lat year join 

。月/年の列の実際の関係に基づいて結合条件を変更します。私は、私はそれらすべてを持って期待し

1

SELECT 
    Current_Month.product_name, units_sold_current_month, 
    units_sold_last_month * 100/units_sold_current_month prc_last_month, 
    units_sold_last_year * 100/units_sold_current_month prc_last_year 
FROM 
    (SELECT product_id, product_name, sum(units_sold) units_sold_current_month FROM MyTable WHERE YEAR = 2011 AND MONTH = 7) Current_Month 
    JOIN 
    (SELECT product_id, product_name, sum(units_sold) units_sold_last_month FROM MyTable WHERE YEAR = 2011 AND MONTH = 6) Last_Month 
    ON Current_Month.product_id = Last_Month.product_id 
    JOIN 
    (SELECT product_id, product_name, sum(units_sold) units_sold_last_year FROM MyTable WHERE YEAR = 2010 AND MONTH = 7) Last_Year 
    ON Current_Month.product_id = Last_Year.product_id 
+0

ええええええええええええええええええええええええええええええええええええ投稿するこれは、前月の値を現在の月のパーセンテージ(私が見る限り)にします。私は結合技術を試みます。 – Perplexed