这是我的表模式的一个人为的版本,用来说明我的问题:
QuoteID,详细信息,DateCreated,ModelQuoteID
其中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
发布于 2012-08-08 04:58:51
看着奥运会--只是浏览一下你的帖子--看起来你想要控制每个级别(根和一个级别)的排序,并确保返回的数据直接在其父数据下的子项(这样您就可以对数据进行分页...)。我们一直都在这么做。您可以向每个内部查询添加一个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
您可以看到根节点是按升序排序的,内部节点是按降序排序的。
https://stackoverflow.com/questions/11857295
复制