SQL Server排序基于两列 - 父级和子级

时间:2012-07-26 08:54:22

标签: sql sql-server-2008 tsql sql-server-2005

我在SQL Server中遇到了排序问题。

我的结果集是主列和辅助列的结果集。辅助列指的是主列的子节点,例如它是稍后出现在结果集

中的主列的id
Primary Column | Secondary Column
1                  NULL
1                  2
1                  3
3                  NULL
3                  NULL
2                  NULL
2                  NULL
2                  7

我需要SQL SELECT按主列排序,但是有一个辅助列会在主列下注入与该id相关的行,例如上面的结果集看起来像。

Primary Column | Secondary Column
1                  NULL
1                  2
2                  NULL
2                  NULL
2                  7
1                  3
3                  NULL
3                  NULL

如果不使用CURSOR

,这在SQL中是否可行

2 个答案:

答案 0 :(得分:2)

试试这个:

with cte as (select *,ROW_NUMBER() over(partition by Primary_Column order by isnull(Secondary_Column,0)) as rownum 
    from test_order
    where Secondary_Column is null or Secondary_Column not in (select Primary_Column from test_order)
), 
cte1 as (
    select *,ROW_NUMBER() over(partition by Secondary_Column order by isnull(Primary_Column,0))-1 as rownum
    from test_order
    where Secondary_Column  in (select Primary_Column from test_order)
),
cte2 as (select 'c1' [type],* from cte
    union all
    select 'c2' [type],* from cte1)
    select Primary_Column,Secondary_Column from cte2
    order by case when [type]='c1' then Primary_Column 
                                else Secondary_Column end,rownum

SQL Fiddle Demo

答案 1 :(得分:2)

一种方法是使用自我加入:

select primary, secondary
from (select t.primary, t.secondary,
             max(case when tsub.primary is not null then 1 else 0 end) as hasprimary
      from t left outer join
           t tsub
           on t.secondary = t.primary
      group by t.primary, t.secondary
     ) a
order by (case when hasprimary = 1 then secondary else primary end),
         hasprimary desc,
         secondary

根据是否存在匹配的行,计算首先使用的ID(主要或次要)。第二个条款将“不寻常”的一个放在首位,然后是其余的。