create table sx
(父级 varchar(5),子级 varchar(5),用量 int)insert into sx
select 'A','B',1 union all
select 'B','C',2 union all
select 'C','D',1 union all
select 'B1','C1',1 union all
select 'X','B',2 union all
select 'X','B1',2
with t as
(select a.父级 '顶层',a.子级,a.用量
from sx a
where not exists(select 1 from sx b where b.子级=a.父级)
union all
select d.顶层,c.子级,c.用量*d.用量
from sx c
inner join t d on c.父级=d.子级
)
select a.顶层,a.子级,a.用量,
case when not exists(select 1 from sx b where b.父级=a.子级)
then '底层' else '' end '标识'
from t a
order by a.顶层/*
顶层 子级 用量 标识
----- ----- ----------- ----
A B 1
A C 2
A D 2 底层
X B 2
X B1 2
X C1 2 底层
X C 4
X D 4 底层(8 row(s) affected)
*/
解决方案 »
- SQL Server表中的计算列的公式中能否引用别的表中的列,如何引用?
- 求一个SQL语句,在线等立即给分100!
- 如何在查询分析器中查询出所有用户库?
- 含标识列的表如何从EXCEL表导入到MS-SQLSERVER数据库中?
- 各位大哥,菜鸟请问???
- 想问下使用MySQL Administrator 1.2时候创建连接的时候如果我的IP是动态的该怎么写Server host哦,
- 我有个小问题
- 系统表systypes中的ID类型是什么类型,表中怎样才能使用此类型????
- 哪里可以下载DB2?有多大?
- 多相同记录查询问题
- 求高手看下如何把此代码改成Sql2000可以用的
- 请问一下SQL应该如何优化
消息 102,级别15,状态1,第12行 't' 附近有语法错误
(父级 varchar(5),子级 varchar(5),用量 int)
insert into sx
select 'A','B',1 union all
select 'B','C',2 union all
select 'C','D',1 union all
select 'B1','C1',1 union all
select 'X','B',2 union all
select 'X','B1',2
;with t as
(select a.父级 '顶层',a.子级,a.用量
from sx a
where not exists(select 1 from sx b where b.子级=a.父级)
union all
select d.顶层,c.子级,c.用量*d.用量
from sx c
inner join t d on c.父级=d.子级
)
select a.顶层,a.子级,a.用量,
case when not exists(select 1 from sx b where b.父级=a.子级)
then '底层' else '' end '标识'
from t a
order by a.顶层;
在SQL 2008中测试OK,谢谢 @唐诗三百首