我想我會發布的另一種方法我工作了,我想沿着dense_rank()
工作其他人都在思考的線條更。這個假設唯一的事情是_order
是一個順序整數(即沒有間隙)。
相同的數據設置爲前:
if object_id('tempdb.dbo.#t') is not null drop table #t
create table #t
(
_order int primary key clustered,
_type int,
_grp int
)
insert into #t (_order, _type)
select 1,7
union all select 2,11
union all select 3,11
union all select 4,18
union all select 5,5
union all select 6,19
union all select 7,5
union all select 8,5
union all select 9,3
union all select 10,11
union all select 11,11
union all select 12,3
什麼此方法確實是row_number
每個_type
,這樣無論在哪裏,一個_type
存在,多少次,該類型將有順序的唯一ROW_NUMBER _order
字段。通過從全局行號中減去該類型特定的行號(即_order
),您將最終得到組。下面是這個代碼,然後我將介紹這一點。
;with tr as
(
select
-- Create an incrementing integer row_number over each _type (regardless of it's position in the sequence)
_type_rid = row_number() over (partition by _type order by _order),
-- This shows that on rows 6-8 (the transition between type 19 and 5), naively they're all assigned the same group
naive_type_rid = _order - row_number() over (partition by _type order by _order),
-- By adding a value to the type_rid which is a function of _type, those two values are distinct.
-- Originally I just added the value, but I think squaring it ensures that there can't ever be another gap of 1
true_type_rid = (_order - row_number() over (partition by _type order by _order)) + power(_type, 2),
_type,
_order
from #t
-- order by _order -- uncomment this if you want to run the inner select separately
)
select
_grp = dense_rank() over (order by max(_order)),
_type = max(_type)
from tr
group by true_type_rid
order by max(_order)
這是怎麼回事
首先第一件事情;我不必在src
cte中創建單獨的列以返回_type_rid
。我主要是爲了排除故障和清晰。其次,我也沒有必要在列_grp
的最後選擇上做第二個dense_rank
。我只是這樣做,所以它完全符合我另一種方法的結果。
在每種類型中,type_rid
是唯一的,並且遞增1. _order
也遞增1。所以只要一個給定的類型沿着,只差1個,_order - _type_rid
將是相同的價值。讓我們看幾個例子(這是src
CTE的結果,通過_order
訂購):
_type_rid naive_type_rid true_type_rid _type _order
-------------------- -------------------- -------------------- ----------- -----------
1 8 17 3 9
2 10 19 3 12
1 4 29 5 5
2 5 30 5 7
3 5 30 5 8
1 0 49 7 1
1 1 122 11 2
2 1 122 11 3
3 7 128 11 10
4 7 128 11 11
1 3 327 18 4
1 5 366 19 6
第一行,_order - _type_rid
= 1 - 1 = 0。這此行(類型7)分配給組0 第二行,2 - 1 = 1。這將類型11分配給組1 第三行,3 - 2 = 1.這將第二個順序類型11分配給組1也 第四行,4 - 1 = 3。鍵入18到組3 ...等等。
這些組不是連續的,而是與_order
的順序相同,這是重要的部分。您還會注意到我也將該值添加爲_type
。這是因爲當我們碰到後面的一些行時,組切換,但是序列仍然增加1.通過添加_type
,我們可以區分那些逐個值,並且仍然按照正確的順序進行。
最終外部從src
訂單由最大(_order)(在我不必要的dense_rank()
_grp修改,只是一般的結果順序)。
結論
這還是有點靠不住,但絕對內的「支持的功能」的界限很好。鑑於我在那裏遇到了一個問題(一件事情),可能還有其他我沒有考慮過的問題,所以再次嘗試一下,做一些測試。
到目前爲止您嘗試過什麼?你的計數邏輯是什麼?如果它只是按類型,不應該類型5計數3而不是2? – Eric
我相信你需要更詳細地解釋你的邏輯。 – ViKiNG
我完全不理解你期望在這裏輸出什麼?你似乎對你想要的東西有非常深刻的理解,但這個解釋對我來說根本沒有任何意義。我正在考慮在刪除答案中發佈的scsimon。 –