如何基于列检查多个条件

时间:2018-01-04 12:44:13

标签: sql tsql

我有一张表,我需要从中找出多个拒绝条件。

我做了以下但不满意并寻找一些好的选择。

declare @tbl table(id int identity, check1 float, check2 float, check3 float)

insert into @tbl (check1, check2, check3)
values (10, 15, 20), (5, 9, 8), (2, 3, 10)

select 
    id, 
    case 
        when check1 < 5 and check2 < 10 and check3 < 15 
           then 'check1 is less than 5 and check2 is less than 10 and check3 is less than 15'
        when check1 < 5 and check2 < 10 
           then 'check1 is less than 5 and check2 is less than 10'
        when check1 < 5 and check3 < 15 
           then 'check1 is less than 5 and check3 is less than 15'
        when check2 < 10 and check3 < 15 
           then 'check2 is less than 10 and check3 is less than 15'
        when check1 < 5 
           then 'check1 is less than 5 '
        when check2 < 10 
           then 'check2 is less than 10 '
        when check3 < 15 
           then 'check3 is less than 15 '
        else 'ok'
    end  
from 
    @tbl      

2 个答案:

答案 0 :(得分:2)

您可以为每个条件使用单独的CASE表达式,然后尝试以某种有意义的方式聚合所有消息。像这样:

WITH cte AS (
    SELECT id,
        CASE WHEN check1 < 5  THEN 'check1 is less than 5'  ELSE 'NA' END AS msg1,
        CASE WHEN check2 < 10 THEN 'check2 is less than 10' ELSE 'NA' END AS msg2,
        CASE WHEN check3 < 15 THEN 'check3 is less than 15' ELSE 'NA' END AS msg3
    FROM @tbl
)

SELECT
    id,
    msg1 + ', ' + msg2 + ', ' + msg3 AS message
FROM cte;

screen capture from demo

Demo

答案 1 :(得分:0)

你可以试试这个。

select * 
    , ISNULL( STUFF(CASE WHEN check1 < 5 THEN 'AND check1 is less than 5 ' ELSE '' END
    + CASE WHEN check2 < 10 THEN 'AND check2 is less than 10 ' ELSE '' END
    + CASE WHEN check3 < 15 THEN 'AND check3 is less than 15 ' ELSE '' END, 1,4,''), 'ok')
from 
@tbl