SQL Server CTE查询未获得所需结果

时间:2017-02-15 04:52:51

标签: sql sql-server sql-server-2008 common-table-expression

我的桌子上有很少的栏目和我正在使用CTE以分层方式按层次顺序获取数据:

Cat 1
--item X1
--item X2
Cat 2
Cat 3
Cat 4
cat 5
--item A1
--item A2
Cat 6 

表格数据:

ID  LanguageID  Name        ParentID    Active
----------------------------------------------
1   1           Cat 1       0           1
2   1           item X1     1           1
3   1           item X2     1           1
4   1           cat 2       0           1
5   1           cat 3       0           0
6   1           cat 4       0           1
7   1           cat 5       0           1
8   1           item A1     7           1
9   1           item A2     7           0
10  1           cat 6       0           1

CTE查询:

WITH CTE (ID, ParentID, Name, LanguageID, Active, Depth, SortCol) AS  
( 
    SELECT 
        ID, ParentID, Name, LanguageID, Active, 0, 
        CAST(ID AS varbinary(max)) 
    FROM 
        Project 
    WHERE 
        ParentID = 0 AND  Active = 1

    UNION ALL

    SELECT 
        d.ID, d.ParentID, d.Name, p.LanguageID, p.Active, p.Depth + 1, 
        CAST(SortCol + CAST(d.ID AS binary(4)) AS varbinary(max)) 
    FROM 
        Project AS d 
    JOIN 
        CTE AS p ON d.ParentID = p.ID
    WHERE 
        p.Active = 1
) 
SELECT 
    ID, ParentID, Name, LanguageID, Active, Depth, 
    REPLICATE('  ', Depth) + Name as HName 
FROM 
    CTE 
WHERE 
    LanguageID = 1 AND  Active = 1
ORDER BY 
    Name

以上查询会隐藏父类别,但不会隐藏子项目。

其次我只能在名称中订购父类别,而不能在子项中订购。

预期输出应为:

Cat 1
--item X1
--item X2
Cat 2
Cat 4
cat 5
--item A1
Cat 6 

更新:只是提到我没有在上面的输出中显示CTE查询的所有列是查询的完整输出

ID  ParentID    Name        LanguageID  Active  Depth   HName
------------------------------------------------------------------
1      0        Cat 1           1           1       0   Cat 1
4      1        item X1         1           1       0   item X1
7      1        item X2         1           1       0   item X2
8      0        cat 2           1           1       1   cat 2
9      0        cat 4           1           1       1   cat 4
10     0        cat 5           1           1       0   cat 5
3      7        item A1         1           1       1   item A1
2      7        item A2         1           1       1   item A2
6      0        cat 6           1           1       0   cat 6

1 个答案:

答案 0 :(得分:0)

你可以在这里使用自我加入。请参阅以下查询

select p.Name, c.Name,c.Active,c.Id,c.LanguageID
From Project c left outer join Project p
where c.ParentId = p.Id