日期:2014-05-17  浏览次数:20581 次

急!简单SQL语句问题
--测试数据
create table #table(year varchar(10),sl varchar(10))
insert into #table
select '2008','20.2'

select * from #table

--查询条件2008年和2013年,则查询结果如下
year sl
2008 20.2
2013 0.00
--注:年度查询条件是动态的,可以是任意年的组合
--如果表中不存在该年度,查询条件的年度全部显示出来,sl字段显示为0.00

------解决方案--------------------
把年份作为变量,执行拼接字符串,行不?
------解决方案--------------------

select number,isnull(sl,0.00)sl from master..spt_values a 
left join #table b on a.number=b.year
where type='p' 
and number in(2008,2013) --这里写条件组合


------解决方案--------------------
create table #table(year varchar(10),sl varchar(10)) 
insert into #table
select '2008','20.2'  
union all select '2012','40.2'  
union all select '2013','50.2'  

select * from #table


declare @s varchar(1000)
set @s='2008,2013'

select * from #table
where case when @s='' then 1 else CHARINDEX(','+cast(year as varchar)+',',','+@s+',') end>0



------解决方案--------------------
2楼正解。。。。。。
------解决方案--------------------
引用:

select number,isnull(sl,0.00)sl from master..spt_values a 
left join #table b on a.number=b.year
where type='p' 
and number in(2008,2013) --这里写条件组合


这个应该可以
------解决方案--------------------
二楼牛人,学习了