由父子进行的SQL分组

时间:2011-03-10 17:11:41

标签: sql

如果我的列有这个结构:

Primary_Key,Name,Parent_Primary_ID,DISPLAY_ORDER

1 Event NULL 1

2 News NULL 2

3 Event_List 1 1

4 Event_Detail 1 2

5 News_List 2 1

6 News_Details 2 2

你会如何返回数据:

1 Event

3 Event_List

4 Event_Detail

2 News

5 News_List

6 News_Detail

由于 罗布

3 个答案:

答案 0 :(得分:2)

如果是SQL Server 2005 +

DECLARE @YourTable TABLE 
(Primary_Key INT PRIMARY KEY,
 Name VARCHAR(100), 
 Parent_Primary_ID INT NULL,
 DISPLAY_ORDER INT)


INSERT INTO @YourTable
SELECT 1,'Event',NULL,1 UNION ALL
SELECT 2,'News',NULL,2 UNION ALL
SELECT 3,'Event_List',1,1 UNION ALL
SELECT 4,'Event_Detail',1,2 UNION ALL
SELECT 5,'News_List',2,1 UNION ALL
SELECT 6,'News_Details',2,2;

WITH Hierarchy
     AS (SELECT *,
                path = CAST(DISPLAY_ORDER AS VARCHAR(100))
         FROM   @YourTable
         WHERE  Parent_Primary_ID IS NULL
         UNION ALL
         SELECT y.Primary_Key,
                y.Name,
                y.Parent_Primary_ID,
                y.DISPLAY_ORDER,
                CAST(path + '.' + CAST(y.DISPLAY_ORDER AS VARCHAR) AS VARCHAR(100))
         FROM   @YourTable y
                JOIN Hierarchy h
                  ON h.Primary_Key = y.Parent_Primary_ID)
SELECT Primary_Key,
       Name
FROM   Hierarchy
ORDER  BY path  

答案 1 :(得分:1)

尝试(支持asumming标准sql)

DECLARE @YourTable TABLE 
(Primary_Key INT PRIMARY KEY,
 Name VARCHAR(100), 
 Parent_Primary_ID INT NULL,
 DISPLAY_ORDER INT)


INSERT INTO @YourTable
SELECT 1,'Event',NULL,1 UNION ALL
SELECT 2,'News',NULL,2 UNION ALL
SELECT 3,'Event_List',1,1 UNION ALL
SELECT 4,'Event_Detail',1,2 UNION ALL
SELECT 5,'News_List',2,1 UNION ALL
SELECT 6,'News_Details',2,2;

select
    primary_key = t1.primary_key,
    name = t1.name
from
    @YourTable t1
    left join @YourTable t2 on t1.parent_primary_id = t2.Primary_Key
order by
    coalesce(t2.DISPLAY_ORDER,t1.DISPLAY_ORDER,0),
    case    
        when t2.Primary_Key is null then 0
        else t1.DISPLAY_ORDER
    end

答案 2 :(得分:0)

我在结果中看不到任何分组。除非您尝试做某事,否则我不会告诉我们,我会使用以下查询:

SELECT Primary_Key, Name FROM YourTable

我不知道你是如何订购这些结果所以我没有尝试订购它们。