求SQL:分类表递归显示
本帖最后由 daisyding1984 于 2013-01-17 11:06:41 编辑 CatId CatName ParentId SortOrder CatAttr
2 产品专区 0 1 1
5 精美饰品 2 1 1
6 女性用品 2 2 1
7 精致礼品 2 3 1
8 日常用品 2 4 1
33 头饰 5 1 0
10 手表 5 2 0
11 挂件 5 3 0
14 彩妆 6 1 0
15 护肤 6 2 0
19 玩具 7 1 0
20 动漫 7 2 0
21 桌游 7 3 0
25 数码配件 8 1 0
26 手提包 8 2 0
27 皮夹 8 3 0
查询结果如下(CatAttr=1,需要在CatName加(封面频道),每一级分类前面要加一个全角空格,按sortOrder排序,不知道SQL查询语句能否实现?
CatName SortOrder
产品专区(封面频道) 1
精美饰品(封面频道) 1
头饰 1
手表 2
挂件 3
女性用品(封面频道) 1
彩妆 1
护肤 2
精致礼品(封面频道) 1
玩具 1
动漫 2
桌游 3
日常用品(封面频道) 1
数码配件 1
手提包 2
皮夹 3
[解决办法]
USE test
GO
-->生成表tb
if object_id('tb') is not null
drop table tb
Go
Create table tb([CatId] smallint,[CatName] nvarchar(4),[ParentId] smallint,[SortOrder] smallint,[CatAttr] bit)
Insert into tb
Select 2,N'产品专区',0,1,1
Union all Select 5,N'精美饰品',2,1,1
Union all Select 6,N'女性用品',2,2,1
Union all Select 7,N'精致礼品',2,3,1
Union all Select 8,N'日常用品',2,4,1
Union all Select 33,N'头饰',5,1,0
Union all Select 10,N'手表',5,2,0
Union all Select 11,N'挂件',5,3,0
Union all Select 14,N'彩妆',6,1,0
Union all Select 15,N'护肤',6,2,0
Union all Select 19,N'玩具',7,1,0
Union all Select 20,N'动漫',7,2,0
Union all Select 21,N'桌游',7,3,0
Union all Select 25,N'数码配件',8,1,0
Union all Select 26,N'手提包',8,2,0
Union all Select 27,N'皮夹',8,3,0
Union all Select 28,N'皮帶手表',10,1,0---- test
Union all Select 29,N'石英手表',10,2,0---- test
;WITH t AS (
SELECT
CatId
,CAST(CatName AS NVARCHAR(50)) AS CatName
,ParentId
,SortOrder
,CatAttr
,1 AS row
,CAST(0 AS INT) AS row1
FROM tb
WHERE ParentId=0
UNION ALL
SELECT
a.CatId
,CAST(REPLICATE(' ',row)+a.CatName AS NVARCHAR(50)) AS CatName
,a.ParentId
,a.SortOrder
,a.CatAttr
,b.row+1
,CAST(CASE WHEN b.ParentId=0 THEN ROW_NUMBER()OVER(ORDER BY a.SortOrder) ELSE b.row1 END AS INT)
FROM tb AS a
INNER JOIN t AS b ON a.ParentId=b.CatId
)
SELECT
CatName+CASE WHEN CatAttr=1 THEN N'(封面频道)' ELSE '' END AS CatName
,SortOrder
FROM t
ORDER BY row1,ParentId,SortOrder
/*
CatName SortOrder
--------------------- ---------
产品专区(封面频道) 1
精美饰品(封面频道) 1
头饰 1
手表 2
挂件 3
皮帶手表 1
石英手表 2
女性用品(封面频道) 2
彩妆 1
护肤 2
精致礼品(封面频道) 3
玩具 1
动漫 2
桌游 3
日常用品(封面频道) 4
数码配件 1
手提包 2
皮夹 3
*/