编码 名称 计算下面有几个直接下级(如下所示)
435 司法的 0
996 死地方 3
99601 沙发斯蒂芬 0
99602 司法所 1
9960201 司法的 0
99603 撒旦法 0
997 萨旦法 0
998 实施的 5
99801 急急急 0
99802 死死地 2
9980201 3lod你 2
998020101 解决的 3
99802010101 及会计 0
99802010102 让人此 0
99802010103 看55 0
998020102 及会计 0
9980203 合计 0
99803 jj看看 0
99806 呵呵 0
99807 和计划 0
999 城乡社 0
如上所列 如何用sql语句计算 是0,2,3,5 等等
435 司法的 0
996 死地方 3
99601 沙发斯蒂芬 0
99602 司法所 1
9960201 司法的 0
99603 撒旦法 0
997 萨旦法 0
998 实施的 5
99801 急急急 0
99802 死死地 2
9980201 3lod你 2
998020101 解决的 3
99802010101 及会计 0
99802010102 让人此 0
99802010103 看55 0
998020102 及会计 0
9980203 合计 0
99803 jj看看 0
99806 呵呵 0
99807 和计划 0
999 城乡社 0
如上所列 如何用sql语句计算 是0,2,3,5 等等
if not object_id('Tempdb..#T') is null
drop table #T
Go
Create table #T([编码] varchar(50),[名称] nvarchar(10))
Insert #T
select 435,N'司法的' union all
select 996,N'死地方' union all
select 99601,N'沙发斯蒂芬' union all
select 99602,N'司法所' union all
select 9960201,N'司法的' union all
select 99603,N'撒旦法' union all
select 997,N'萨旦法' union all
select 998,N'实施的' union all
select 99801,N'急急急' union all
select 99802,N'死死地' union all
select 9980201,N'3lod你' union all
select 998020101,N'解决的' union all
select 99802010101,N'及会计' union all
select 99802010102,N'让人此' union all
select 99802010103,N'看55' union all
select 998020102,N'及会计' union all
select 9980203,N'合计' union all
select 99803,N'jj看看' union all
select 99806,N'呵呵' union all
select 99807,N'和计划' union all
select 999,N'城乡社'
Go
Select a.[编码],a.名称,COUNT(b.编码) as 直属
from #T as a
left join #T as b on b.[编码] like a.[编码]+'__'
group by a.[编码],a.名称
order by 1
/*
编码 名称 直属
435 司法的 0
996 死地方 3
99601 沙发斯蒂芬 0
99602 司法所 1
9960201 司法的 0
99603 撒旦法 0
997 萨旦法 0
998 实施的 5
99801 急急急 0
99802 死死地 2
9980201 3lod你 2
998020101 解决的 3
99802010101 及会计 0
99802010102 让人此 0
99802010103 看55 0
998020102 及会计 0
9980203 合计 0
99803 jj看看 0
99806 呵呵 0
99807 和计划 0
999 城乡社 0
*/
直属数量=(select count(1) from tb where 编码 like a.编码+'%')
from tb a
直属数量=(select count(1) from tb where 编码 like a.编码+'__')
from tb a
直属数量=(select count(1) from #T where 编码 like a.编码+'%' and (len(编码) = 5))
from #T a
From #T a
Left Outer join #T b on b.编码 like a.编码+'%' and a.编码!=b.编码
Left Outer Join #T c on b.编码 like c.编码+'%' and a.编码!=c.编码 and b.编码!=c.编码 and Len(c.编码)>Len(a.编码)
Where Not (b.编码 Is Not Null and c.编码 Is Not Null)
Group by a.编码,a.名称
order by a.编码虽然语句写已经能满足你的需求了,但个人建议楼主,这个表的结构最好加一个层级的字段这样楼主想要的结果应该会很容易实现,而且前端实现的代码也很容易判断。