码迷,mamicode.com
首页 > 数据库 > 详细

SQL 树结构统计数据

时间:2016-06-18 15:20:52      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:


create table #Tmp
(
ID int IDENTITY (1,1) not null,
name varchar(50),
sl int
);

DECLARE @ID VARCHAR(36)
SET @ID = ‘7197ccfb-f01d-437f-9059-f4b821ebf2e1‘
;WITH T AS
(
SELECT ID , parentid , NAME
FROM Base_SXZD
WHERE ID = @ID
UNION ALL
SELECT A.ID , A.parentid , A.NAME
FROM Base_SXZD AS A JOIN T AS B ON A.parentid = B.id
)
insert into #Tmp
select name=(select name from Base_SXZD where id=‘7197ccfb-f01d-437f-9059-f4b821ebf2e1‘),sl = sum(m.sl) from (
select a.id, a.name,count(b.id) as sl from T a
left join jxxt_ajlb b on a.id = b.ajlxid
" + GetIfWhere(all, ajly) + @"
group by a.id,a.name) m


SET @ID = ‘5090a923-3c1a-4628-95ae-12edf10d41ae‘
;WITH T AS
(
SELECT ID , parentid , NAME
FROM Base_SXZD
WHERE ID = @ID
UNION ALL
SELECT A.ID , A.parentid , A.NAME
FROM Base_SXZD AS A JOIN T AS B ON A.parentid = B.id
)
insert into #Tmp
select name=(select name from Base_SXZD where id=‘5090a923-3c1a-4628-95ae-12edf10d41ae‘),sl = sum(m.sl) from (
select a.id, a.name,count(b.id) as sl from T a
left join jxxt_ajlb b on a.id = b.ajlxid
" + GetIfWhere(all, ajly) + @"
group by a.id,a.name) m


SET @ID = ‘91322101-c2cb-47bd-91ce-69418722d835‘
;WITH T AS
(
SELECT ID , parentid , NAME
FROM Base_SXZD
WHERE ID = @ID
UNION ALL
SELECT A.ID , A.parentid , A.NAME
FROM Base_SXZD AS A JOIN T AS B ON A.parentid = B.id
)
insert into #Tmp
select name=(select name from Base_SXZD where id=‘91322101-c2cb-47bd-91ce-69418722d835‘),sl = sum(m.sl) from (
select a.id, a.name,count(b.id) as sl from T a
left join jxxt_ajlb b on a.id = b.ajlxid
" + GetIfWhere(all, ajly) + @"
group by a.id,a.name) m

select ID,name, isnull(sl,0) as ajsl from #Tmp
drop table #Tmp

SQL 树结构统计数据

标签:

原文地址:http://www.cnblogs.com/ssk-bak/p/5596156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!