有没有办法从sql server case/when语句中的“then”运行select语句? (我需要从 then 语句运行子查询。)我不能在 where 语句中使用它。
select
case @Group
when 6500 then (select top 10 * from Table1)
when 5450 then (select top 5 * from Table1)
when 2010 then (select top 3 * from Table1)
when 2000 then (select top 1 * from Table1)
else 0
end as 'Report'
最佳答案
一种选择是从查询中删除它并执行以下操作:
declare @Numrows int;
select @Numrows = (case @Group
when 6500 then 10
when 5450 then 5
when 2010 then 3
when 2000 then 1
else 0
end);
select top(@NumRows) *
from Table1;
你也可以这样做:
with const as (
select (case @Group
when 6500 then 10
when 5450 then 5
when 2010 then 3
when 2000 then 1
else 0
end) as Numrows
)
select t.*
from (select t.*, ROW_NUMBER() over () as seqnum
from table1 t
) t cross join
const
where seqnum <= NumRows;
在这种情况下,您需要列出列以避免获取
seqnum
在列表中。顺便说一句,通常在使用
top
时你也应该有 order by
.否则,结果是不确定的。
关于sql - 在 then of case when 语句中选择子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15795224/