日期:2014-05-19  浏览次数:20364 次

数据查询显示?
测试数据如下:
declare   @a   table(年   int,   月   int,   数量   int,   名称   varchar(19),编号   varchar(10))
insert   @a   select   2007   ,3   ,20   , '鼠标 ', '01 '
union   all   select   2007   ,4   ,26   , '鼠标 ', '01 '
union   all   select   2008   ,1   ,21   , '光驱 ', '02 '
union   all   select   2007   ,3   ,24   , '硬盘 ', '03 '  
union   all   select   2007   ,4   ,26   , '硬盘 ', '03 '

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  

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

现在把数据改成
declare   @a   table(年   int,   月   int,   数量   int,   名称   varchar(19),编号   varchar(10))
insert   @a   select   2007   ,3   ,20   , '鼠标 ', '01 '
union   all   select   2007   ,4   ,26   , '鼠标a ', '01 '
union   all   select   2008   ,1   ,21   , '光驱 ', '02 '
union   all   select   2007   ,3   ,24   , '硬盘 ', '03 '  
union   all   select   2007   ,4   ,26   , '硬盘 ', '03 '

说明:字段名称里的内容可以不同,主要根据编号来判断,但查询显示名称要以月份大的。
查询效果如下:
名称           年             编号       4月                 3月
鼠标a       2007             01           26                 20


------解决方案--------------------
declare @a table(年 int, 月 int, 數量 int, 名稱 varchar(19),編號 varchar(10))
insert @a select 2007 ,3 ,20 , '鼠標 ', '01 '
union all select 2007 ,4 ,26 , '鼠標a ', '01 '
union all select 2008 ,1 ,21 , '光驅 ', '02 '
union all select 2007 ,3 ,24 , '硬盤 ', '03 '
union all select 2007 ,4 ,26 , '硬盤 ', '03 '



select t1.名稱,t1.年,t2.編號,t2.[4月],t2.[3月] from @a t1
left join (select max(case when 月= '04 ' then [數量] end) as [4月] ,max(case when 月= '03 ' then [數量] end) as [3月] ,編號 from @a group by 編號) t2
on t1.編號=t2.編號
where t1.月= '04 ' and t2.[4月]> t2.[3月]*1.2


/*
名稱 年 編號 4月 3月
-----------------------------------
鼠標a 2007 01 20 26

*/