我的情况是我需要从固定列表中生成多行 固定列表有 11 行,我需要从中选择可变数量的行
我可以这样做
select r.ritid, r.loadfactor, cvirtual.ProductSequence from rit r outer apply ( select top 5 --r.loadfactor RitID, CarID, row_number() over (partition by RitID order by RitID) as ProductSequence from ( values(r.RitID, 1), (r.RitID, 2), (r.RitID, 3), (r.RitID, 4), (r.RitID, 5), (r.RitID, 6), (r.RitID, 7), (r.RitID, 8), (r.RitID, 9), (r.RitID, 10), (r.RitID, 11) ) as X(RitID, CarId) --where c.CarID is null ) cvirtual --on r.RitID = cvirtual.RitID
这将使我从列表中获得 5 行, 但我不想写top 5,但类似的东西top r.LoadFactor是不可能的。
top 5
top r.LoadFactor
那么,我该怎么做呢? 请不要使用动态sql
你可以在这里找到一个 DBFiddle
如果表rit中的列LoadFactor是 3,那么我想要这个结果
rit
LoadFactor
ritid loadfactor ProductSequence 1 5 1 1 5 2 1 5 3
如果表rit中的列LoadFactor是 5,那么我想要这个结果
ritid loadfactor ProductSequence 1 5 1 1 5 2 1 5 3 1 5 4 1 5 5
可以与列一起使用top,如您在此db<>fiddle中看到的,但您需要在列名周围添加括号,例如top(r.loadfactor)。
top
top(r.loadfactor)
所以如果r.loadfactor是 3 它将只返回 3 行,如果它是 5 它将返回 5 行。只需添加order by到top结果中。
r.loadfactor
order by
使用 on loadfactor 运行查询,update如下所示:
update
update rit set loadfactor = 3 select r.ritid, r.loadfactor, cvirtual.ProductSequence from rit r outer apply ( select top(r.loadfactor) RitID, CarID, row_number() over (partition by RitID order by RitID) as ProductSequence from ( values(r.RitID, 1), (r.RitID, 2), (r.RitID, 3), (r.RitID, 4), (r.RitID, 5), (r.RitID, 6), (r.RitID, 7), (r.RitID, 8), (r.RitID, 9), (r.RitID, 10), (r.RitID, 11) ) as X(RitID, CarId) --where c.CarID is null ) cvirtual --on r.RitID = cvirtual.RitID
回报:
+------+------------+-----------------+ | ritid| loadfactor | ProductSequence | +------+------------+-----------------+ |1 | 3 | 1 | |1 | 3 | 2 | |1 | 3 | 3 | +------+------------+-----------------+