一条SQL查询语句的写法解决办法
一条SQL查询语句的写法
字符串S为 "1,5,8"
某表A内容如下
字段:a1 a2 a3
5 9 7
1 3 4
2 6 1
我想要两个查询语句
第一个语句要得知字符串S 在表A中存在几个值,比如本例实际就存在2个值:5和1 (8不存在)
查询语句要得到的结果就是2
第二个语句要得知字符串S中的数值,在表A中分别有几个,比如本例1就有两个,5有一个,8没有
------解决方案--------------------
字符串S为 "1,5,8"
某表A内容如下
字段:a1 a2 a3
5 9 7
1 3 4
2 6 1
我想要两个查询语句
第一个语句要得知字符串S 在表A中存在几个值,比如本例实际就存在2个值:5和1 (8不存在)
查询语句要得到的结果就是2
第二个语句要得知字符串S中的数值,在表A中分别有几个,比如本例1就有两个,5有一个,8没有
------解决方案--------------------
- SQL code
--> 测试数据: @表A declare @表A table (a1 int,a2 int,a3 int) insert into @表A select 5,9,7 union all select 1,3,4 union all select 2,6,1 declare @s varchar(10) set @s='1,5,8' select a1,count(1) as cnt from ( select a1 from @表A union all select a2 from @表A union all select a3 from @表A ) a where charindex(','+ltrim(a1)+',',','+@s+',')>0 group by a1 /* a1 cnt ----------- ----------- 1 2 5 1 */