按字段排序查询与另一个字段相关

时间:2017-01-24 13:44:55

标签: sql sql-server sorting

我的SQL Server数据库中有一个名为dayorder的表,其中包含以下字段:

dayorder_cod (autoinc id),
dayorder_number (order number),
dayorder_sequence (order sequence)
dayorder_parent (parent order, can be null).

所以我可以订购100,200,998和999,其中100是998和999的母公司。

我想按如下方式对结果进行排序:100,998,999,200,即订单的子项位于其父级之下。

2 个答案:

答案 0 :(得分:4)

不需要加入:

如果dayorder_parent引用dayorder_number,则:

select d.*
from dayorder d
order by 
  isnull(d.dayorder_parent,d.dayorder_number)
  , d.dayorder_number

如果dayorder_parent引用dayorder_cod,则:

select d.*
from dayorder d
order by 
  isnull(d.dayorder_parent,d.dayorder_cod)
  , d.dayorder_cod

如果dayorder_sequence对订单重要

select d.*
from dayorder d
order by 
  isnull(d.dayorder_parent,d.dayorder_cod)
  , d.dayorder_sequence

工作原理:查询结果按dayorder_parent排序,但每个订单的初始行的NULL值为dayorder_parent

使用isnull(d.dayorder_parent,d.dayorder_number)我们可以说当订单没有父订单时,请改用dayorder_number。 100名儿童与100名儿童分组,每组进一步按其个人dayorder_number排序。

注意:您可以使用coalesce()代替isnull()来获得相同的结果。我倾向于仅在需要从一组3个或更多值中获取第一个非空值时使用coalesce(),因为isnull()仅支持两个参数。

答案 1 :(得分:3)

试试这个:

SELECT t1.*
FROM dayorder AS t1
LEFT JOIN dayorder AS t2 ON t2.parent = t1.cod
ORDER BY COALESCE(t2.parent, t1.cod), t1.cod

修改

如果sequence字段确定表格中的顺序,则可以使用:

SELECT t1.*
FROM dayorder AS t1
LEFT JOIN dayorder AS t2 ON t2.parent = t1.cod
ORDER BY COALESCE(t2.sequence, t1.sequence), t1.sequence