SOS!!sql语句汇总查询,复杂,诡异,超难解决,急!!!

afengelf 2012-02-07 11:44:26
我先描述下我遇到的难题:
我现在手里有一个表,里面记录着一些单位统计到的数据,但是统计到的数据都是该单位本身的。
而我需要的数据是汇总的数据,意思是说我需要得到单位本身的数据和该单位所有下级单位(如果该单位有下级的话)的数据之和

关于表结构、单位层级关系、我需要统计的数据我都用下图画出来了
表一:单位表
id varchar(50)
name varchar(50)
parent varchar(50)
ancestor varchar(50)

表二:单位本身的统计数据
t1_id varchar(50)
count int

图片中“我希望统计后的数据”是单位本身的数据加上该单位所有下级单位的数据之和。
例如id为10001的单位它有10002、10003、10004,所以10001的汇总后的count为39
例如10003的单位它有一个下级10004,所以10003的汇总后的count为30

哪位高手能帮我解决这个问题啊,卡了好几天了!

图:
...全文
214 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
叶子 2012-02-08
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 afengelf 的回复:]
厉害厉害,不过能不能不用临时表,直接用sql语句来实现啊
[/Quote]
公用表表达式 (CTE)和临时表不是一个概念
777kit 2012-02-08
  • 打赏
  • 举报
回复
SELECT id,
(
SELECT SUM(count)
FROM T2
WHERE t1_id IN (SELECT id FROM T1 WHERE id = a.id OR ancestor LIKE '%' + a.id + '%')
)
FROM T1 a
AcHerat 2012-02-07
  • 打赏
  • 举报
回复

create table t1(id int,[name] varchar(100),parent int)
insert into t1
select 10000,'xx1',0 union all
select 10001,'xx2',10000 union all
select 10002,'xx3',10001 union all
select 10003,'xx4',10001 union all
select 10004,'xx5',10003 union all
select 10005,'xx6',10000
go

create table t2(id int,cnt int)
insert into t2
select 10001,5 union all
select 10002,4 union all
select 10003,10 union all
select 10004,20 union all
select 10005,12
go

;with cte as
(
select id,cnt,id as po from t2
union all
select t.id,b.cnt,a.id
from t1 a join cte t on a.parent = t.po
join t2 b on a.id = b.id
)

select id,sum(cnt) cnt
from cte
group by id

drop table t1,t2

/****************

id cnt
----------- -----------
10001 39
10002 4
10003 30
10004 20
10005 12

(5 行受影响)
afengelf 2012-02-07
  • 打赏
  • 举报
回复
sql 2008
AcHerat 2012-02-07
  • 打赏
  • 举报
回复
SQL是2000还是05或08?
simplecao2012 2012-02-07
  • 打赏
  • 举报
回复
不懂递归吖,能不能输出3L 那个cte子表给我看看,顺便简单讲解一下?
苦苦的潜行者 2012-02-07
  • 打赏
  • 举报
回复
很好的题目,正好我想练练cte递归,拿走了,另外把lz的图贴上.
AcHerat 2012-02-07
  • 打赏
  • 举报
回复
这涉及到递归的一些处理,如果按照某条SQL语句来处理,可能需要加一个得到子级的函数,按函数来做。
afengelf 2012-02-07
  • 打赏
  • 举报
回复
厉害厉害,不过能不能不用临时表,直接用sql语句来实现啊

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧