sql查询来计算每月增长百分比

时间:2011-07-06 14:03:18

标签: sql sql-server-2005

我需要构建一个包含4列的查询(sql 2005)。

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

在我的表中,年份和月份都有自定义整数值。例如,最近一个月是146 - 而且该表还有一年(例如2011年)列和月(例如7)列。

是否可以在一个查询中完成此操作,或者我是否需要开始使用临时表等?

感谢任何帮助。

感谢,

KS

3 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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时。