代码之家  ›  专栏  ›  技术社区  ›  Jeremiah Williams

SQLServer基于前100个结果在查询中创建案例

  •  -1
  • Jeremiah Williams  · 技术社区  · 8 年前

    我正在尝试根据以下条件创建SQL Server查询:

    查询集中在三列:Report\u Status、Error\u Message和Create\u Date。查询的目的是根据Create\U日期筛选前100个最新结果。完成后,它需要查看排名前100位的Report\u Status中的每一行是否都显示“Failed”,并且Error\u消息是否不包含“Placement is missing%”。

    如果满足这些条件,则需要输出消息“潜在服务故障”如果它不满足这些条件,那么它要么什么都不做,要么输出一些正常的东西,比如“没有发现问题”

    我想用一个案例可能是最好的方法,所以我尝试了一下。不过,我很难让它正常工作:

    select Report_Status, Error_Message, Create_Date,
    case
         when Report_Status = 'Failed' and Error_Message not like 'Placement is missing%' then 'Potential service failure.'
         ELSE 'No problems found.'
    end
    from [AUDIT_TABLE] limit 100
    

    这是解决这个问题的最佳方法吗?如果是这样的话,我需要做什么改变才能工作?如果这不是一个好方法,有什么更好的方法来解决这个问题?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Gordon Linoff    8 年前

    您似乎想要这样的东西:

    select (case when count(*) = 100 then 'Potential service failure.'
                 else 'No problems found.'
            end) as summary
    from (select a.*
          from [AUDIT_TABLE]
          order by date desc
          fetch first 100 rows only
         ) t100
    where Report_Status = 'Failed' and
          Error_Message not like 'Placement is missing%'
    
        2
  •  0
  •   Jeremiah Williams    8 年前

    最后我和一个同事一起解决了这个问题。Gordon Linoff的案例部分很棒,但我们通过使用Report\u ID字段改变了搜索最近100条记录的方式。

    select
     (case when count(*) = 100 then 'Potential failure.'
            else 'No problems found.'
        end) as Result
     from Audit_Table
    where Report_Status = 'fail' 
        and  Error_Message not like 'Placement is missing%'
        and  Report_ID >= (select min(Report_ID) from (select top 100 * from Audit_Table  order by Report_ID desc ) t100)