SQL IIF

时间:2017-04-05 10:27:26

标签: sql sql-server

  select studentnr, result, 
            iif(result>= 5.5, 'yes', 'no') as passed
    from grade

给我

| Studentnr | Result  | Passed            |
|-----------|---------|-------------------|
| 101       | 6.5     | Yes               |

但我正在努力实现

| Studentnr | Result  | Passed            |
|-----------|---------|-------------------|
| 101       | 6.5     | Yes lower than 7  |
| 102       | 8       | Yes higher than 7 |
| 103       | 4.5     | No                |

有没有办法用IIF做到这一点?

4 个答案:

答案 0 :(得分:2)

使用嵌套的IIF语句可以

示例:

SELECT IIF(a.results > 5.5, 

            --Another IIF if it's higher than 5.5
            IIF(a.results <= 7, 'Yes lower than 7', 'Yes higher than 7'), 

            -- else no.
            'No' ) AS Passed
FROM (
      VALUES (4), (6), (8)
     ) AS a(results);

但是,我完全同意@Stefano和@Utsav的观点。如果您需要嵌套IIFs,那么我认为您也可以使用CASE语句。

SELECT CASE WHEN a.results > 7 THEN 'Yes higher than 7'
            WHEN a.results <= 7 AND a.results >= 5.5 THEN 'Yes lower than 7'
            ELSE 'No'
       END AS Passed
FROM (
      VALUES (4), (6), (8)
     ) AS a(results);

答案 1 :(得分:0)

不确定IIF是什么,但您可以使用case来实现相同目标。

select studentnr, result, 
case when result>= 5.5 then 'Yes' 
    else 'No' 
end as passed,
case when result>= 7 then 'Higher than 7' 
    else 'Lower than 7' 
end as gt_lt_7
from grade

答案 2 :(得分:0)

您可以使用case语句返回单个列

select studentnr,
       result, 
       case
           when grade <= 5.5 then 'no'
           when grade between 6 and 7 then 'yes, lower'
           else 'yes, higher'
       end as passed
from grade

如果您需要两个单独的列,则可以将case添加到您编写的if

select studentnr,
       result, 
       iif(result >= 5.5, 'yes', 'no') as passed,
       case
           when grade <= 5.5 then '-'
           when grade between 6 and 7 then 'lower'
           else 'higher'
       end as hi_lo
from grade

答案 3 :(得分:0)

;WITH cte1(studentnr,result)
As
(
SELECT 101,4.5 Union all
SELECT 102,5.5 Union all
SELECT 103,6.5 Union all
SELECT 104,7.5 Union all
SELECT 105,6.5 Union all
SELECT 106,4.5 Union all
SELECT 107,8.5
)
,cte2 AS (
        SELECT studentnr
            ,Result
            ,CASE 
                WHEN result >= 5.5  THEN 'YES'
                WHEN result <= 4.5  THEN 'NO'
                END As Results
        FROM cte1
        )

SELECT CONCAT('studentnr : ',studentnr) AS studentnr
    ,CONCAT('Result : ',result)AS Result
    ,CASE 
        WHEN Results = 'YES' AND result < 7
                THEN 'Passed: Yes lower than 7'
            WHEN Results = 'YES' AND result > 7
                THEN 'Passed: Yes higher than 7'
        WHEN Results = 'NO'
                THEN 'Passed: NO'
        END AS FinalResult
FROM cte2