2017-04-05 61 views
0
select studentnr, result, 
      iif(result>= 5.5, 'yes', 'no') as passed 
    from grade 

給我多項標準SQL IIF

| 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做到這一點?

回答

2

This is可能使用嵌套的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); 
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 
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 
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