按日期降序对父行进行排序,子行在每行下独立排序



这是我的表模式的人为版本,用于说明我的问题:

报价ID, 详细信息, 创建日期, 模型报价ID

其中 QuoteID 是主键,ModelQuoteID 是返回此表的可为空的外键,以表示已从另一个报价建模的报价(并且随后可能更改了其详细信息列等)。

我需要返回按 DateCreated 降序排序的报价列表,但建模报价除外,它应该位于其父报价下方,在任何其他同级报价中按日期降序排序(报价只能建模一级深度)。

因此,例如,如果我有以下 4 个引号行:

1, 'Fix the roof', '01/01/2012', null
2, 'Clean the drains', '02/02/2012', null
3, 'Fix the roof and door', '03/03/2012', 1
4, 'Fix the roof, door and window', '04/04/2012', 1
5, 'Mow the lawn', '05/05/2012', null

然后我需要按以下顺序返回结果:

5 - Mow the lawn
2 - Clean the drains
1 - Fix the roof
4 - -> Fix the roof, door and window
3 - -> Fix the roof and door

我还传递了搜索条件,例如详细信息的关键字,并且即使它们不包含搜索词,但其父引用包含,我也会返回建模引号。我让该部分使用通用表表达式来获取原始引号,并与建模引号的连接联合起来。

这很好用,但目前我不得不将建模的引号重新排列成代码中的正确顺序。这并不理想,因为我的下一步是在 SQL 中实现分页,如果当时行没有正确分组,那么我将不会让当前页面中的子项在代码中进行重新排序。一般来说,无论如何,它们都会自然地组合在一起,但并非总是如此。您可以立即为一个月前的报价创建一个模型报价。

我花了很多时间在这上面,任何SQL大师都可以提供帮助吗?非常感谢。

编辑:这是我的SQL的人为版本,以适应我人为的例子:-)

;with originals as (
select
    q.*
from
    Quote q
where
    Details like @details
)
select
    *
from
(
select
    o.*
from
    originals o
union
select
    q2.*
from
    Quote q2
join
    originals o on q2.ModelQuoteID = o.QuoteID
)
as combined
order by
    combined.CreatedDate desc

观看奥运会 - 刚刚浏览了你的帖子 - 看起来你想控制每个级别(根和一级)的排序,并确保返回的数据与子级直接在其父级下方(这样你就可以分页数据...... 我们一直在这样做。 可以向每个内部查询添加order by并创建sort列。 我设计了一个稍微不同的例子,你应该很容易应用到你的情况。 我对根升序和一级降序进行了排序,只是为了说明如何控制每个部分。

declare @tbl table (id int, parent int, name varchar(10))
insert into @tbl (id, parent, name)
values (1, null, 'def'), (2, 1, 'this'), (3, 1, 'is'), (4, 1, 'a'), (5, 1, 'test'),
       (6, null, 'abc'), (7, 6, 'this'), (8, 6, 'is'), (9, 6, 'another'), (10, 6, 'test')
;with cte (id, parent, name, sort) as (
  select id, parent, name, cast(right('0000' + cast(row_number() over (order by name) as varchar(4)), 4) as varchar(1024))
  from   @tbl
  where  parent is null
  union all
  select t.id, t.parent, t.name, cast(cte.sort + right('0000' + cast(row_number() over (order by t.name desc) as varchar(4)), 4) as varchar(1024))
  from   @tbl t inner join cte on t.parent = cte.id
)
select * from cte
order by sort

这将产生以下结果:

id    parent    name     sort
----  --------  -------  ----------
6     NULL      abc      0001
7     6         this     00010001
10    6         test     00010002
8     6         is       00010003
9     6         another  00010004
1     NULL      def      0002
2     1         this     00020001
5     1         test     00020002
3     1         is       00020003
4     1         a        00020004

您可以看到根节点按升序排序,内部节点按降序排序。

最新更新