SQL在另一个中按值排序一列

时间:2015-03-15 15:46:13

标签: sql sql-server

我正在尝试从SQL中排序结果,以便缩进的BOM以正确的顺序嵌套值。我得到了'#34; hard"递归部分完成,但现在正确地嵌套结果证明比我想象的更成问题。到目前为止,我在相当广泛的研究中似乎没有任何重复的这个问题。

这是我的数据:

+------+------------+-------+-----+-------+
| Root | Assemblys  | Items | Qty | Depth |
+------+------------+-------+-----+-------+
| Root | Assembly   | Item1 | 1   |     0 |
| Root | Item1      | Item2 | 3   |     1 |
| Root | Item1      | Item3 | 4.6 |     1 |
| Root | Item2      | Item4 | 1.5 |     2 |
| Root | Item2      | Item5 | 22  |     2 |
| Root | Item3      | Item6 | 6   |     2 |
+------+------------+-------+-----+-------+

我要做的是对列进行排序,以便一列跟随另一列的值。请注意Item1如何将其组件移动到项目行中后立即移动?我试图弄清楚如何使用一列来对另一列进行排序,但到目前为止我还没有尝试过任何运气。

+------+-----------+-------+-----+-------+
| Root | Assemblys | Items | Qty | Depth |
+------+-----------+-------+-----+-------+
| Root | Assembly  | Item1 | 1   |     0 |
| Root | Item1     | Item2 | 3   |     1 |
| Root | Item2     | Item4 | 1.5 |     2 |
| Root | Item2     | Item5 | 22  |     2 |
| Root | Item1     | Item3 | 4.6 |     1 |
| Root | Item3     | Item6 | 6   |     2 |
+------+-----------+-------+-----+-------+

Here is a SQL Fiddle

1 个答案:

答案 0 :(得分:2)

您可以使用递归CTE,如下所示:

;with cte as (
   select *, cast([Item] as nvarchar(max)) as [path] from IndentedBOM where Depth = 0

   union all

   select i.*, c.[path] + '/' + i.[Item]
   from cte as c
       inner join IndentedBOM as i on i.[Assembly] = c.[Item]
)
select *
from cte
order by [path]

sql fiddle demo

相关问题