我有一個 5 欄位表,我想做一個這樣的 qry:
SELECT *
FROM dbo.table
WHERE somefield in (90,120,30,90)
問題是我在表的行中有幾個 90、120 和 30 個值,但我只想回傳與條件匹配的前 4 行。
有什么簡單的方法可以做到這一點?我在 SQL Server 2008 上。
CREATE TABLE ForgeRock
([id] int, [somefield] int)
;
INSERT INTO ForgeRock
([id], [somefield])
VALUES
(1, 90),
(2, 90),
(3, 120),
(4, 30),
(5, 30),
(6, 90),
(7, 10),
(8, 20),
(9, 90),
(10, 30),
(11, 20)
;
處理資料和查詢。預期的結果將是90,120,20,90和他們尊重id的。
uj5u.com熱心網友回復:
您按串列過濾,并in檢查每個輸入值的成員資格。因此,串列中值的序數位置無關緊要,它僅用于過濾。要區分相同值的兩個不同實體,您需要將此串列轉換為表格或進行其他一些保存訂單資訊的轉換。
一種方法可以是表值建構式:
with flt as (
select
val,
row_number() over(partition by val order by val) as rn /*To distinguish instances of the value*/
from(values (90),(120),(30),(90)) as t(val)
)
, base as (
select
f.*,
row_number() over(partition by somefield order by id) as rn
from ForgeRock as f
where somefield in (select flt.val from flt) /*To restrict input before row number*/
)
select b.*
from base as b
join flt
/*Match value AND repetition*/
on b.somefield = flt.val
and b.rn = flt.rn
ID 某地 rn 4 30 1 1 90 1 2 90 2 3 120 1
對于現代版本,也有openjson的可能性,如果您從外部收到此串列:
with flt as (
select
[value] as val,
row_number() over(partition by [value] order by [key]) as rn /*To distinguish instances of the value*/
from openjson('[90, 120, 30, 90]') as t
)
...
the same code
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419941.html
標籤:
下一篇:如何通過表中的特定值設定條件行號
