递归SQL关系查询

时间:2013-08-14 15:26:00

标签: sql sql-server

我被困在一个SQL查询上,任何人都可以帮助我吗? 以下是我的表[LEVEL]

使用列

Id int, Name Varchar(50), ObjectId Int, ParentId Int, LevelId int

以下是记录:

INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('Test',1,NULL,1);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('3rdItem',2,1,2);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('1stItem',3,2,3);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('ehs',4,3,4);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('2ndItem',5,3,4);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('test tom',6,3,4);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('waterweg23',7,3,4);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('ehs',4,2,1);

我需要让父母拥有最高等级ID的对象。

这里记录“ehs”有2个父母,即(3& 2)它应该只显示父母3的ehs,因为对象3的级别ID高于2。

所以我想获得父级有max levelId

的所有记录

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

如果你想要递归的,试试这个:

with cte as (
    select L.Name, L.ObjectId, L.LevelID, L.ParentId, LP.LevelId as ParentLevelId
    from [LEVEL] as L
        left outer join [LEVEL] as LP on LP.ObjectID = L.ParentId
    union all
    select L.Name, L.ObjectId, L.LevelID, c.ParentId, c.ParentLevelId
    from [LEVEL] as L
        inner join cte as c on c.ObjectId = L.ParentId
), cte2 as (
    select
        Name, ObjectID, ParentId, LevelId, ParentLevelId,
        row_number() over(partition by Name, ObjectID order by ParentLevelId desc) as row_num
    from cte
)
select
    Name, ObjectID, LevelId, ParentId, ParentLevelId
from cte2
where row_num = 1
order by name asc

sql fiddle

答案 1 :(得分:0)

试试这个。

DECLARE @LEVEL TABLE (Id int, Name Varchar(50), ObjectId Int, ParentId Int, LevelId int)

INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('Test',1,NULL,1);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('3rdItem',2,1,2);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('1stItem',3,2,3);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('ehs',4,3,4);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('2ndItem',5,3,4);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('test tom',6,3,4);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('waterweg23',7,3,4);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('ehs',4,2,1);

SELECT
    l.ID,
    l.Name,
    l.ObjectID,
    l.ParentID,
    l.LevelID
FROM
    @LEVEL AS l INNER JOIN (
                        SELECT
                            ObjectID,
                            MAX(LevelID) AS LevelID
                        FROM
                            @LEVEL
                        GROUP BY
                            ObjectID
                        ) AS s
                    ON
                        l.ObjectID = s.ObjectID
                            AND
                        l.LevelID = s.LevelID
ORDER BY
    l.ObjectID