数据查询显示?
测试数据如下:
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月
-----------------------------------
鼠a2007012026
*/