微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

sql – 选择子查询里面的case语句何时?

有没有办法在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时你也应该有订单.否则,结果是不确定的.

原文地址:https://www.jb51.cc/mssql/76766.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐