27,580
社区成员
发帖
与我相关
我的任务
分享
declare @categorytree table(id int ,parentId int, categoryID int)
insert into @categorytree select
1,0,1 union all select
2,0,2 union all select
3,1,3 union all select
4,3,4 union all select
5,2,7
declare @category table (categoryID int, categoryName varchar(10), level int)
insert into @category select
1 ,'企划', 1 union all select
2 ,'开发', 1 union all select
3 ,'年度计划', 2 union all select
4 ,'项目A', 3 union all select
7 ,'模块开发', 2
declare @categorylevel table (level int ,categorylevelName varchar(10))
insert into @categorylevel select
1 ,'分类一' union all select
2 ,'分类二' union all select
3 ,'分类三'
;with cte as
(select id ,parentId , categoryID ,level=1 from @categorytree
union all
select c.id ,t.parentId,c.categoryID,level=c.level+1
from @categorytree t inner join cte c
on t.id=c.parentID
)
,cte2 as (select a.*,categoryname=isnull(c.categoryname,b.categoryname),d.categorylevelname from cte a left join @category b
on a.categoryID=b.categoryID
left join @category c on a.parentID = c.categoryID
left join @categorylevel d on a.level=d.level
)
select id,[分类一],[分类二],[分类三]
from (select id,categoryname,categorylevelname from cte2 ) src
pivot (max(categoryname) for categorylevelname in ([分类一],[分类二],[分类三]))as p
IF OBJECT_ID('tempdb..#Categorytree','U') IS NOT NULL DROP TABLE #Categorytree
CREATE TABLE #Categorytree
(
ID INT
,ParentID INT
,CategoryID INT
)
INSERT INTO #Categorytree
SELECT 1, 0, 1 UNION ALL
SELECT 2, 0, 2 UNION ALL
SELECT 3, 1, 3 UNION ALL
SELECT 4, 3, 4 UNION ALL
SELECT 5, 2, 7
IF OBJECT_ID('tempdb..#Categorytree','U') IS NOT NULL DROP TABLE #Category
CREATE TABLE #Category
(
CategoryID INT
,CategoryName NVARCHAR(20)
,LevelID INT
)
INSERT INTO #Category
SELECT 1, N'企划', 1 UNION ALL
SELECT 2, N'开发', 1 UNION ALL
SELECT 3, N'年度计划', 2 UNION ALL
SELECT 4, N'项目A', 3 UNION ALL
SELECT 7, N'模块开发', 2
IF OBJECT_ID('tempdb..#Categorytree','U') IS NOT NULL DROP TABLE #Categorylevel
CREATE TABLE #Categorylevel
(
LevelID INT
,CategorylevelName NVARCHAR(20)
)
INSERT INTO #Categorylevel
SELECT 1,N'分类一' UNION ALL
SELECT 2,N'分类二' UNION ALL
SELECT 3,N'分类三'
DECLARE @ID INT =4
;WITH CTE(ID)
AS (
SELECT CategoryID
FROM #Categorytree
WHERE ID=@ID
UNION ALL
SELECT ParentID
FROM CTE AS A
JOIN #Categorytree AS B ON A.ID=B.CategoryID
WHERE ParentID>0
)
SELECT *
FROM (
SELECT C.CategorylevelName,B.CategoryName
FROM CTE AS A
JOIN #Category AS B ON A.ID=B.CategoryID
JOIN #Categorylevel AS C ON B.LevelID=C.LevelID
) T
PIVOT(MAX(CategoryName) FOR CategorylevelName IN([分类一],[分类二],[分类三])) p
没看懂。。瞎写的。。