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

SQL CTE 数据汇总

时间:2015-05-13 12:07:35      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

if exists (select * from sysobjects where name=‘Test‘)  

  drop table test;

go

create table Test

(

ID int, --ID

Name nvarchar(50), --名称

Total int, --总量

FinishedTotal int, --完成量

ParentID int,--父ID

Level int--层级

)

insert into Test values(1, ‘A‘, 0,0,null,0);

insert into Test values(2, ‘AA‘, 0,0,1,1);

insert into Test values(3, ‘BB‘, 0,0,1,1);

insert into Test values(4, ‘AAA‘, 0,0,2,2);

insert into Test values(5, ‘BBB‘, 5,5,2,2);

insert into Test values(6, ‘AAAA‘, 10,10,4,3);

insert into Test values(7, ‘BBBB‘, 10,10,4,3);

insert into Test values(8, ‘CCCC‘, 10,10,4,3);

insert into Test values(9, ‘DDDD‘, 10,10,4,3);

insert into Test values(10, ‘EEEE‘, 0,0,5,3);

with Cte1 as (

select ID,Name,ParentID,Total ,FinishedTotal,Level FROM Test

union all

select T.ID,T.Name,T.[ParentID], Cte1.Total,Cte1.FinishedTotal,T.Level from Test T 

inner join

Cte1 on T.ID=Cte1.ParentID

)

select ID,Name,ParentID,T.Total ,T.FinishedTotal, A.Total as Total1,A.FinishedTotal as FinishedTotal1,Level FROM Test T

cross apply

(

select isnull(sum(Total),0) as Total,

isnull(sum(FinishedTotal),0) as FinishedTotal

from Cte1 where T.ID=Cte1.ID

) A order by ID

SQL CTE 数据汇总

标签:

原文地址:http://www.cnblogs.com/TpLife/p/4499868.html

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