2011-07-06 99 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)列。

是否有可能在一個查詢中完成此操作,或者是否需要開始使用臨時表等?

感謝任何幫助。

感謝,

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 

如果有一個地方產品在一個月內出售,但不是再過一個月,你就必須做一個左連接,並檢查空值,特別是如果last_month.sales或last_year.sales 0的情況下。

+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,並查看這三個銷售數字是否正確。我只是對我的一個本地表運行這個,它給出了正確的百分比,所以我想看看查詢計算的是什麼值。問候,布賴恩 –

+0

Nvm我得到它的工作! – Perplexed

1

我猜測略有所提供的表的結構是結果表,對不對?您需要做一個月至以前逐月自聯接:

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 

其中<growth computation here>看起來像

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

我用LEFT 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