我的select语句最后有问题。我想要做的是选择两个级别,但我没有得到这个声明的结果。请注意,如果@Level为1,我不想小于1,否则可能会导致结果混乱,因此可能存在条件
它所在的部分@Level = @Level -1我遇到了
的问题FROM c WHERE c.Level = @Level AND c.Level = @Level - 1 ORDER BY Level ASC
或者这个
FROM c WHERE c.Level BETWEEN @Level AND c.Level - 1 ORDER BY Level ASC
SQL
DECLARE @Department TABLE
(
Id INT NOT NULL,
Name varchar(50) NOT NULL,
ParentId int NULL
)
INSERT INTO @Department SELECT 1, 'Toys', null
INSERT INTO @Department SELECT 2, 'Computers', null,
INSERT INTO @Department SELECT 3, 'Consoles', 2
INSERT INTO @Department SELECT 4, 'PlayStation 3', 3
INSERT INTO @Department SELECT 5, 'Xbox 360', 2
INSERT INTO @Department SELECT 6, 'Games', 1
INSERT INTO @Department SELECT 7, 'Puzzles', 6
INSERT INTO @Department SELECT 8, 'Mens Wear', null
INSERT INTO @Department SELECT 9, 'Mens Clothing', 8
INSERT INTO @Department SELECT 10, 'Jackets', 9
INSERT INTO @Department SELECT 11, 'Shoes', 9
INSERT INTO @Department SELECT 12, 'Rain Coats', 10
DECLARE @Level int = 4
;WITH c AS
(
SELECT Id, ParentId, Name, 1 AS Level
FROM @Department
WHERE ParentId IS NULL
UNION ALL
SELECT t.Id, t.ParentId, T.Name, c.Level + 1 AS Level
FROM @Department T
INNER JOIN c on t.ParentId = c.Id
)
SELECT Id, ParentId, Name, Level
FROM c WHERE c.Level = @Level AND c.Level = @Level - 1 ORDER BY Level ASC
FROM c WHERE c.Level BETWEEN @Level AND @Level - 1 ORDER BY Level ASC
答案 0 :(得分:2)
也许FROM c WHERE c.Level BETWEEN @Level -1 AND @Level ORDER BY Level ASC
答案 1 :(得分:1)
这里的代码从不能够工作:
@Level = @Level - 1
我想你想说:
c.Level = @Level - 1
即便如此......你可能想要OR
而不是AND
。
考虑一下你要问的内容......"同时向我提供级别为4和5的所有记录。"
你的意思可能是......"给我所有水平为4或5的记录。"
答案 2 :(得分:0)
看看下面的SQL,它返回4行3级和1级4级:
SELECT p.Id as ParentId,
p.Name as Parent,
c.Id,
c.Name,
c.Level
FROM c as c
left join c p
on p.Id = c.ParentId
WHERE c.Level = @Level
ORDER BY p.Name, c.Name ASC
答案 3 :(得分:0)
好的,您的递归CTE似乎正确。我通常不会将name
放在CTE中(主要是因为表只是父/子字段,或者有太多),然后加入,但它应该仍然可以正常工作。
正如已经指出的,你真正的问题是你的where
条款是非感性的:
WHERE c.Level = @Level AND c.Level = @Level - 1
基本上询问c.level == c.Level - 1
- 总是是否为假。WHERE c.Level BETWEEN @Level AND @Level - 1
要求@Level >= c.Level >= @Level - 1
或@Level >= @Level - 1
- 另一个不可能的条件。如果稍加修改,这些方法中的任何一种都应该可以正常工作:
WHERE c.Level = @Level OR c.Level = @Level - 1
WHERE c.Level BETWEEN @Level - 1 AND @Level
(@Level
输入为1
无关紧要 - 因为您开始为1,因此报告的级别没有更低级别。