sql: T-SQL 统计计算(父子關係,樹形,分級分類的統計)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
---sql: T-SQL 统计计算(父子關係,樹形,分級分類的統計)
---2014-08-26 塗聚文(Geovin Du)
CREATE PROCEDURE proc_Select_BookKindSumReport
AS
DECLARE @temp TABLE
(
      BookKindID INT IDENTITY(1, 1) ,
      BookKindName  VARCHAR(10),
      BookKindParent int,
      BookKindSum int
)
--
declare @id int,@grouid nvarchar(500),@sql nvarchar(4000),@cstucount int,@c int
DECLARE @tempId INT ,
    @tempName VARCHAR(10),
    @tempParent int
drop table #temp
select * into #temp from BookKindList
WHILE EXISTS ( SELECT   BookKindID FROM   #temp )
    BEGIN 
        SET ROWCOUNT 1  
        SELECT  @tempId = [BookKindID] ,
                @tempName = [BookKindName],
                @tempParent=BookKindParent
        FROM    #temp 
        SET ROWCOUNT 0 
--
delete from #temp where BookKindID = @tempId
        set @id=@tempId
        select  @grouid=dbo.GetBookKindGroupId (@id)
select @sql='SELECT @c=count(*) FROM BookInfoList where BookInfoKind in ('+@grouid+')'
--exec (@sql)
exec sp_executesql @sql,N'@c int output',@cstucount output--将exec的结果放入变量中的做法
--select @cstucount  as 'sum'     
        --PRINT '记录:----'+ cast(@tempId as varchar(20))+',' + @tempName+','+ cast(@tempParent as varchar(20))+' sum:'+ cast(@cstucount as varchar(50))
insert into @temp(BookKindName,BookKindParent,BookKindSum) values(@tempName,@tempParent,@cstucount)
END
select * from @temp order by BookKindParent
GO
 
 
 
--利用游标来遍历表
--定义表变量
DECLARE @temp TABLE
(
      BookKindID INT IDENTITY(1, 1) ,
      BookKindName  VARCHAR(10),
      BookKindParent int
 
DECLARE @tempId INT ,
    @tempName VARCHAR(10),
    @tempParent int
DECLARE test_Cursor CURSOR LOCAL FOR
SELECT   BookKindID,BookKindName,BookKindParent FROM @temp
--插入数据值
INSERT  INTO @temp VALUES  ( 'a',1 )
INSERT  INTO @temp VALUES  ( 'b',2 )
INSERT  INTO @temp VALUES  ( 'c',3 )
INSERT  INTO @temp VALUES  ( 'd',4 )
INSERT  INTO @temp VALUES  ( 'e',5 )
--打开游标
OPEN test_Cursor
WHILE @@FETCH_STATUS = 0
    BEGIN 
        FETCH NEXT FROM test_Cursor INTO @tempId,@tempname,@tempParent
        PRINT '记录:----' + cast(@tempId as varchar(20))+',' + @tempName+','+ cast(@tempParent as varchar(20)) 
    END
CLOSE test_Cursor
DEALLOCATE test_Cursor

 

posted @   ®Geovin Du Dream Park™  阅读(795)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2010-08-26 csharp webform Button控件OnClick,OnClientClick事件
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示