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

请高手帮我看看这样的sql怎么写呀 谢谢
有这样一个表:有四个字段
ID,Name,Totals,Condition。
其中Condition字段保存的是Totals满足的条件,如“Totals <100”   意思是Totals字段值小于100。

具体演示数据如下:
ID       Name       Totals       Condition
1         A             10               Totals <100
2         A             102             Totals <100
3         B             40               Totals <60
4         B             50               Totals <100
5         B             150             Totals <100
6         C             100             Totals <60

现在要查询满足Condition字段条件的所有记录。

其结果是:
ID       Name       Totals       Condition
1         A             10               Totals <100
3         B             40               Totals <60
4         B             50               Totals <100

请大家指点一下     在线等     谢谢!

------解决方案--------------------
--建立环境

create table r(
ID int,
Name varchar(10),
Totals int,
Condition varchar(30)
)
insert r select
1, 'A ', 10 , 'Totals <100 '
union all select
2, 'A ', 102 , 'Totals <100 '
union all select
3, 'B ', 40 , 'Totals <60 '
union all select
4, 'B ', 50 , 'Totals <100 '
union all select
5, 'B ', 150 , 'Totals <100 '
union all select
6, 'C ', 100 , 'Totals <60 '

--查询
declare @sql varchar(8000)
set @sql= ' '

select @sql=@sql+ ' or id= '+cast(id as varchar)+ ' and '+Condition from r

set @sql=stuff(@sql,1,3, ' ')

exec( 'select * from r where '+@sql)

--结果
D Name Totals Condition
----------- ---------- ----------- ------------------------------
1 A 10 Totals <100
3 B 40 Totals <60
4 B 50 Totals <100

--删除环境
drop table r

------解决方案--------------------

select *
from table
where Totals <right(Condition,charindex( ' < ',REVERSE(Condition))-1)