本人想要实现某产品的销量统计,算法如下:
前两天的销量比较:如果前天比昨天高,则标记为正1;低,则标记为负1;
若持平,则标记为0. 并且按销量由高到低排序。
求高手一条sql解决(多条也行)。
已知条件:
表名:goods, 商品名:goodsname,交易时间:goodstime,销量:saleamount.
其中,商品有20种,记录估计1000条。
说明:只求sql,不用考虑其他sql意外的问题。
select a.goodsname,(case when a.前天销售>a.昨天销售 then 1 when a.前天销售=a.昨天销售 then 0 else -1 end) as 销售情况 from(select g.goodsname,sum(case when datediff(day,g.goodstime,getdate())=2 then g.saleamount) as 前天销售额,sum(case when datediff(day,g.goodstime,getdate())=1 then g.saleamount) as 昨天销售 from goods g) a order by a.昨天销售
select case when (select count(1) from goods where id=a.id and datediff(day,goodstime, getdate())>1 group by goodsname) >(select count(1) from goods where id=a.id and datediff(day,goodstime, getdate())>0 group by goodsname) then 1 when (select count(1) from goods where id=a.id and datediff(day,goodstime, getdate())>1 group by goodsname) =(select count(1) from goods where id=a.id and datediff(day,goodstime, getdate())>0 group by goodsname) then 0 else -1 end from goods as a
您好!答案还是比较正确的,只是这样的统计还有些许不足。应该是我描述不够清楚造成的。需求是按商品名称来分组,当天销量来排行,升降统计是按照昨天和前天某商品的销量来统计的。最后得到的结果是:销量第一:火星;销量趋势:上升。销量第二:木星;销量趋势,下降。等等……期待高手的答案。