有张表
年 月 数量 名称
2007 3 20 鼠标
2007 4 26 鼠标
2008 1 21 光驱
2007 3 24 硬盘
2007 4 26 硬盘 要查询2007年4月比2007年3月数量大20%名称列出来
效果如下:
名称 年 4月数量 3月数量
鼠标 2007 26 20
年 月 数量 名称
2007 3 20 鼠标
2007 4 26 鼠标
2008 1 21 光驱
2007 3 24 硬盘
2007 4 26 硬盘 要查询2007年4月比2007年3月数量大20%名称列出来
效果如下:
名称 年 4月数量 3月数量
鼠标 2007 26 20
insert @a select 2007 ,3 ,20 ,'鼠标'
union all select 2007 ,4 ,26 ,'鼠标'
union all select 2008 ,1 ,21 ,'光驱'
union all select 2007 ,3 ,24 ,'硬盘'
union all select 2007 ,4 ,26 ,'硬盘'select * from
(
select 名称,年,
[4月]=sum(case when 月=4 then 数量 else 0 end),
[3月]=sum(case when 月=3 then 数量 else 0 end)
from @a group by 名称,年
) aa
where [4月]>[3月]*1.2
/*
名称 年 4月 3月
-------- ----- ----- -----
鼠标 2007 26 20 (所影响的行数为 1 行)
*/
insert test select 2007,3,20,'鼠标'
union all select 2007,4,26,'鼠标'
union all select 2008,1,21,'光驱'
union all select 2007,3,24,'硬盘'
union all select 2007,4,26,'硬盘'select 名称,年,[4月数量]=sum(case when 月=4 then 数量 end),
[3月数量]=sum(case when 月=3 then 数量 end)
from test
group by 名称,年
having
(sum(case when 月=4 then 数量 end)*1.0
-sum(case when 月=3 then 数量 end))/sum(case when 月=3 then 数量 end)=0.3名称 年 4月数量 3月数量
---------- ----------- ----------- -----------
鼠标 2007 26 20
select 名称,年,[4月数量]=sum(case when 月=4 then 数量 end),
[3月数量]=sum(case when 月=3 then 数量 end)
from test
group by 名称,年
having
(sum(case when 月=4 then 数量 end)*1.0
-sum(case when 月=3 then 数量 end))/sum(case when 月=3 then 数量 end)>0.2