按表在sql中使用父列排序

时间:2014-05-20 06:25:51

标签: sql sql-server tsql sql-order-by

我有一个定义了父列的表。

enter image description here

我需要像这样

订购PARENT_A列这个表

enter image description here

我怎么能用t-sql做到这一点?

感谢。

2 个答案:

答案 0 :(得分:2)

如果您的评论似乎只有两个级别,那么这很简单:

SELECT A,Parent_A
FROM UnnamedTable
ORDER BY
  CASE WHEN Parent_A = 0 THEN A ELSE Parent_A END,  --Sort parents together with their children
  Parent_A --Ensure parents sort before their children

如果实际上有多个级别,那么你需要使用类似递归CTE的东西:

declare @t table (
    A int not null,
    Parent_A int not null)
insert into @t (A,Parent_A) values
(1,0),(2,0),(3,1),(4,2),(5,3)

;With Hier as (
    select A,'/' + CONVERT(varchar(max),A) + '/' as position
    from @t where Parent_A = 0
    union all
    select t.A,position + CONVERT(varchar(max),t.A) + '/'
    from Hier h
        inner join
        @t t
            on
                h.A = t.Parent_A
), Converted as (
    select A,CONVERT(hierarchyid,position) as position
    from Hier
)
select t.A,t.Parent_A
from Converted c
      inner join
     @t t
      on c.A = t.A
order by c.position

答案 1 :(得分:0)

试试这个

;WITH TableA AS (
  SELECT 1 AS pk,0 AS REF
  UNION ALL
  SELECT 2,0
  UNION ALL
  SELECT 3,1
  UNION ALL
  SELECT 4,2
), CTE AS (
  SELECT pk AS masterid, pk AS basePK, REF AS baseRef
  FROM TableA
  WHERE REF = 0
  UNION ALL
  SELECT B.masterid, A.pk, A.REF
  FROM TableA AS A
  INNER JOIN CTE AS B ON B.basePK = A.REF
  WHERE A.REF <> 0
)
SELECT * FROM CTE
ORDER BY masterid,basepk