sql难题:排序,比较统计
本人想要实现某产品的销量统计,算法如下:
前两天的销量比较:如果前天比昨天高,则标记为正1;低,则标记为负1;
若持平,则标记为0. 并且按销量由高到低排序。
求高手一条sql语句解决(多条也行)。
已知条件:
表名:goods, 商品名:goodsname,交易时间:goodstime,销量:saleamount.
其中,商品有20种,记录估计1000条。
说明:只求sql,不用考虑其他sql语句以外的问题。
------解决方案----------------------查看模拟数据
select goodsname,goodstime,saleamount from goods
/* 模拟数据
a 2012-12-10 00:00:00.000 5
a 2012-12-10 00:00:00.000 4
a 2012-12-09 00:00:00.000 5
a 2012-12-09 00:00:00.000 3
b 2012-12-10 00:00:00.000 5
b 2012-12-10 00:00:00.000 4
b 2012-12-09 00:00:00.000 5
b 2012-12-09 00:00:00.000 4
c 2012-12-10 00:00:00.000 6
c 2012-12-10 00:00:00.000 4
c 2012-12-09 00:00:00.000 5
c 2012-12-09 00:00:00.000 3
d 2012-12-10 00:00:00.000 5
d 2012-12-10 00:00:00.000 4
e 2012-12-09 00:00:00.000 5
e 2012-12-09 00:00:00.000 3
*/
-- 统计 goodsname 商品名称, Comparison 比较结果, mountYesterday 昨天销售量, mountBeforeYesterday 前天销售量
select goodsname
,case when isnull(mountBeforeYesterday,0)> isnull(mountYesterday,0) then 1 when isnull(mountBeforeYesterday,0)< isnull(mountYesterday,0) then -1 else 0 end Comparison
,isnull(mountYesterday,0) mountYesterday,isnull(mountBeforeYesterday,0) mountBeforeYesterday
from
(select distinct goodsname from goods) t
left join (
select sum(a.saleamount) mountYesterday,a.goodsname gnYesterday
from goods a
where convert(varchar(10),a.goodstime,23) =convert(char(10), dateadd(day,-1,getdate()),23)
group by a.goodsname
) t1 on t1.gnYesterday=t.goodsname
left join (
select sum(b.saleamount) mountBeforeYesterday,b.goodsname gnBeforeYesterday
from goods b
where convert(varchar(10),b.goodstime,23) =convert(char(10), dateadd(day,-2,getdate()),23)
group by b.goodsname
) t2 on t2.gnBeforeYesterday=t.goodsname
/* 统计结果
a -1 9 8
b 0 9 9
c -1 10 8
d -1 9 0
e 1 0 8
*/
------解决方案----------------------上个忘排序了,呵呵
--注意,测试数据 12月11日有效
--查看模拟数据
select goodsname,goodstime,saleamount from goods
/* 模拟数据
a 2012-12-10 00:00:00.000 5
a 2012-12-10 00:00:00.000 4
a 2012-12-09 00:00:00.000 5
a 2012-12-09 00:00:00.000 3
b 2012-12-10 00:00:00.000 5
b 2012-12-10 00:00:00.000 4
b 2012-12-09 00:00:00.000 5
b 2012-12-09 00:00:00.000 4
c 2012-12-10 00:00:00.000 6
c 2012-12-10 00:00:00.000 4
c 2012-12-09 00:00:00.000 5
c 2012-12-09 00:00:00.000 3
d 2012-12-10 00:00:00.000 5
d 2012-12-10 00:00:00.000 4
e 2012-12-09 00:00:00.000 5
e 2012-12-09 00:00:00.000 3
*/
-- 统计 goodsname 商品名称, Comparison 比较结果, mountYesterday 昨天销售量, mountBeforeYesterday 前天销售量,total 销售量
select goodsname