质疑上周按销售额计算的顶级产品涨幅

时间:2015-07-07 06:32:25

标签: sql sql-server select top-n

我有一个包含三列的数据库表。

WeekNumberProductNameSalesCount

样本数据如下表所示。我希望在第26周比前一周(即第25周)获得前10名获利者(按%计算)。唯一的条件是该产品在两周内的销售数量应大于0。

在样本数据B中,C,D是常见产品,C具有最高的%增益。

同样,我也需要十大输家。

我到目前为止尝试的是在两周之内进行内部联接并获得常见产品。但是,我无法获得顶级赢家的逻辑。

enter image description here

输出应该像

 Product    PercentGain

  C            400%

  D            12.5%

  B            10%

3 个答案:

答案 0 :(得分:4)

这将为您提供一般答案,而不仅仅是针对任何特定的一周:

select top 10 product , gain [gain%]
from 
(
SELECT product, ((curr.salescount-prev.salescount)/prev.salescount)*100 gain 
from   
  (select weeknumber, product, salescount from tbl) prev
  JOIN
  (select weeknumber, product, salescount from tbl) curr
on prev.weeknumber = curr.weeknumber - 1
AND prev.product = curr.product
where prev.salescount > 0 and curr.salescount > 0
)A 
order by gain desc

如果您对第25周和第26周感兴趣,那么只需在WHERE子句中添加以下条件:

and prev.weeknumber = 25

答案 1 :(得分:1)

如果您使用的是SQL-Server 2012(或更新版本),则可以使用lag功能将“此”周销售额与前一周相匹配。从那以后,这只是一些数学:

SELECT   TOP 10 product, sales/prev_sales - 1 AS gain
FROM     (SELECT product, 
                 sales, 
                 LAG(sales) OVER (PARTITION BY product 
                                  ORDER BY weeknumber) AS prev_sales
          FROM   mytable) t
WHERE    weeknumber = 26 AND
         sales > 0 AND
         prev_sales > 0 AND
         sales > prev_sales
ORDER BY sales/prev_sales

答案 2 :(得分:1)

这是查询。

select top 10 product , gain [gain%]
from 
(
SELECT curr.Product, ( (curr.Sales - prev.Sales ) *100)/prev.Sales gain 
from   
  (select weeknumber, product, sales from ProductInfo where weeknumber = 25 ) prev
  JOIN
  (select weeknumber, product, sales from ProductInfo where weeknumber = 26 ) curr
on    prev.product = curr.product
where prev.Sales > 0 and curr.Sales > 0
)A 
order by gain desc