Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL中创建顺序范围?_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

如何在SQL中创建顺序范围?

如何在SQL中创建顺序范围?,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有一个表,其中每行有一个From和一个To: From|To A | B C | D B | C D | E 我需要按顺序排列,第一行的“to”是下面的“From”,以此类推 结果应按如下顺序排列: From|To A| B B| C C| D D| E 主要问题是查找上一条记录中To之后的From 去 ffrom | fto :---- | :-- a | b c | d e | f g

我有一个表,其中每行有一个From和一个To:

From|To  
  A | B 
  C | D
  B | C
  D | E
我需要按顺序排列,第一行的“to”是下面的“From”,以此类推

结果应按如下顺序排列:

From|To 
   A| B  
   B| C  
   C| D  
   D| E
主要问题是查找上一条记录中To之后的From

ffrom | fto :---- | :-- a | b c | d e | f g | h ffrom | fto :---- | :-- a | b c|d e | f g | h
我不确定你的问题是否正确。你为什么不整理一下呢

;with cte as
(  
select 'B' as "From", 'C' as "To"
union
select 'A', 'B'
union
select 'C', 'D'
)
select "From", "To"
  from cte
 order by "From";
(查询中不需要cte/union内容,只是为了示例数据。)

如果只想列出具有后续项的条目:

;with cte as
(  
select 'B' as "From", 'C' as "To"
union
select 'A', 'B'
union
select 'C', 'D'
union
select 'F', 'G'
)
select "From", "To"
  from cte
 where exists(select *
                from cte cte2
               where cte2."From" = cte."To")
    or exists(select *
                from cte cte3
               where cte3."To" = cte."From")
 order by "From";

顺便说一句:尝试使用除“From”和“To”之外的其他列名,因为它们是必须与“”(ANSI)或[](T SQL)一起使用的保留语句。

您可以使用递归CTE:

with cte as (
      select from, to, 1 as lev
      from t
      where not exists (select 1 from t t2 where t2.to = t.from)
      union all
      select t.from, t.to, cte.lev + 1
      from cte join
           t
           on cte.to = t.from
     )
select to, from
from cte
order by lev, to;

请注意,这受最大递归深度的影响,但它在四行上可以正常工作。

请问您的RDBMS是什么?另外,您能否澄清您是否已经有一个表与第二个结果相似,并且正在努力排序,或者您正试图创建从第一个结果发布的第二个结果?对不起,这是MS SQL server 2008,是否可能出现类似
A | D
的情况?怎么点的?
with cte as (
      select from, to, 1 as lev
      from t
      where not exists (select 1 from t t2 where t2.to = t.from)
      union all
      select t.from, t.to, cte.lev + 1
      from cte join
           t
           on cte.to = t.from
     )
select to, from
from cte
order by lev, to;