1

我在 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 中是否可行

4

2 回答 2

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 小提琴演示

于 2012-07-26T09:31:26.680 回答
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 - 主要或次要。第二个子句将“不寻常的”放在第一位,然后是其余的。

于 2012-07-26T11:11:41.280 回答