查询以获取上周销售额最高的产品获得者

Query to get top product gainers by sales over previous week

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

WeekNumberProductNameSalesCount

示例数据如下所示table。我想要第 26 周比前一周(即第 25 周)排名前 10 的获利者(按百分比)。唯一的条件是产品在这两个星期的销售额都应大于 0。

示例数据中B、C、D为常见产品,C的增益百分比最高。

同样,我也需要前 10 名失败者。

到目前为止我尝试的是在两周内进行内部连接并获得共同产品。但是,我无法获得最高收益者的逻辑。

输出应该像

 Product    PercentGain

  C            400%

  D            12.5%

  B            10%

这会给你一个通用的答案,而不仅仅是针对任何特定的一周:

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

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

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

这是查询。

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