我写的如下:
select 成员,count(成员) as 出现的次数
from a
where 成员 like '%这里不知道怎么写了%'
group by 成员
...全文
3413打赏收藏
这个SQL语句如何写?
有两个表A B A表: a_id 成员 ------------- 1 张三,李四 2 王五、赵六 ..... B表 b_id 姓名 ------------- 1 张三 2 李四 3 王五 .... 现想分类汇总B中人在A中的出现次数 我写的如下: select 成员,count(成员) as 出现的次数 from a where 成员 like '%这里不知道怎么写了%' group by 成员
select cc.d,count(cc.b) from (
select aa.b b,bb.d d
from(
select 成员 b, 姓名 d from A,B where instr(成员,姓名)>0) aa,B bb
where aa.d(+)=bb.d) cc
group by cc.d
declare @A table(a_id int,成员 varchar(20))
insert into @a
select 1,'张三,李四,张三'
union all select 2,'王五,赵六,张三'
declare @B table(b_id int,姓名 varchar(10))
insert into @b
select 1,'张三'
union all select 2,'李四'
union all select 3,'王五'
--创建数据分拆的临时表
select top 8000 id=identity(int,1,1) into #tb
from(select top 100 id from syscolumns) a,
(select top 100 id from syscolumns) b,
(select top 100 id from syscolumns) c
select a.姓名,次数=sum(case when b.姓名 is null then 0 else 1 end)
from @B a left join
(
select 姓名=substring(成员,b.id,charindex(',',成员+',',b.id)-b.id)
from @a a,#tb b
where substring(','+成员,b.id,1)=','
) b on a.姓名=b.姓名 group by a.姓名
如果不是的话,需要用下面的处理方法.
--创建数据分拆的临时表
select top 8000 id=identity(int,1,1) into #tb
from(select top 100 id from syscolumns) a,
(select top 100 id from syscolumns) b,
(select top 100 id from syscolumns) c
--得到结果
select a.姓名,次数=sum(case when b.姓名 is null then 0 else 1 end)
from B a left join
(
select 姓名=substring(成员,b.id,charindex(',',成员+',',b.id)-b.id)
from A a,#tb b
where substring(','+成员,b.id,1)=','
) b on a.姓名=b.姓名 group by a.姓名