2011-07-06 95 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