首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

数据比较,该如何解决

2012-03-21 
数据比较有张表年月数量名称2007320鼠标2007426鼠标2008121光驱2007324硬盘2007426硬盘要查询2007年4月比2

数据比较
有张表
                    年               月             数量         名称
2007             320             鼠标                
2007             426             鼠标                
2008             121             光驱                
2007             324             硬盘              
2007             426             硬盘  

要查询2007年4月比2007年3月数量大20%名称列出来    
效果如下:
名称       年       4月数量         3月数量    
鼠标     2007         26                     20

[解决办法]
declare @a table(年 int, 月 int, 数量 int, 名称 varchar(19))
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

[解决办法]
create table test(年 int,月 int,数量 int,名称 varchar(10))
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

热点排行