[英]row_number with partition value changing
我有這段sql代碼,它根據表__working中的某些值查找row_number,表__working加入查找表__Eval中
;WITH r
AS (
select
w.uid,
t.TypeId,
--weight
ROW_NUMBER () OVER (PARTITION BY w.uid ORDER BY DIFFERENCE(t.val1, w.val1) + DIFFERENCE(t.val2, w.val2) + DIFFERENCE(t.val3, w.val3) + DIFFERENCE(t.val4, w.val4) DESC) as Score
,w.account
from __Working w
join __eval t on w.val1 like t.val1 and IsNull(w.val4, '') like t.val4 and IsNull(w.val2, '') like t.val2 and IsNull(w.val3, '') like t.val3
)
select * from r where r.account = 1 and score = 1
這將返回一個typeId = 1
但是如果我這樣寫
;WITH r
AS (
select
w.uid,
t.TypeId,
--weight
ROW_NUMBER () OVER (PARTITION BY w.uid ORDER BY DIFFERENCE(t.val1, w.val1) + DIFFERENCE(t.val2, w.val2) + DIFFERENCE(t.val3, w.val3) + DIFFERENCE(t.val4, w.val4) DESC) as Score
,w.account
from __Working w
join __eval t on w.val1 like t.val1 and IsNull(w.val4, '') like t.val4 and IsNull(w.val2, '') like t.val2 and IsNull(w.val3, '') like t.val3
where r.account = 1
)
select * from r where r.account = 1 and score = 1
它返回TypeId =2。我希望,如果在__working中跨不同帳戶使用多個UID,但我沒有。 我在這里想念什么?
哦,這是一種不穩定的怪異現象。 您的row_number()
表達式為:
ROW_NUMBER() OVER (PARTITION BY w.uid
ORDER BY DIFFERENCE(t.val1, w.val1) +
DIFFERENCE(t.val2, w.val2) +
DIFFERENCE(t.val3, w.val3) +
DIFFERENCE(t.val4, w.val4) DESC
) as Score
問題是多個行的ORDER BY
鍵具有相同的值。 不同的調用可以任意選擇多個行中的哪一個是第一行,第二行,依此類推。
規范的解決方案是包括某種唯一鍵,以便這種鍵是穩定的:
ROW_NUMBER() OVER (PARTITION BY w.uid
ORDER BY (DIFFERENCE(t.val1, w.val1) +
DIFFERENCE(t.val2, w.val2) +
DIFFERENCE(t.val3, w.val3) +
DIFFERENCE(t.val4, w.val4)
) DESC,
?? -- perhaps typeId
) as Score
但是,我可能會建議一個更艱巨的解決方案。 接受關系可能存在的事實,並使用rank()
和dense_rank()
進行識別。 然后, 明確找出在打平領帶的情況下該怎么做-也許所有事情對您來說都同樣有趣,或者您可能還有其他打平領帶的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.