基于案例的查询

时间:2014-01-31 09:41:08

标签: sql sql-server

我有一张员工表如下:

    ID|description|Grade I|Grade II|
    1|Permanent   |       |T       |
    2|Temp        |T      |        |
    3|Permanent   |       |        |

“成绩”列符合“优秀”或“良好”的要求;具体取决于上述哪些列不为空 我需要编写一个查询,它提供以下输出:

 ID|description
    1|Permanent(Excellent)
    2|Temp(Good)
    3|Permanent

我在Sql Server 2008上 感谢帮助。

2 个答案:

答案 0 :(得分:1)

 create table #employee (ID INT,DESCRIPTION VARCHAR(20),GradeI varchar(20),GradeII VARCHAR(20))
 INSERT INTO #employee VALUES(1,'Permanent',NULL,'T')
 INSERT INTO #employee VALUES(2,'Temp','T',NULL)
 INSERT INTO #employee VALUES(3,'Permanent',NULL,NULL)

SELECT id ,DESCRIPTION,CASE WHEN GradeI IS NOT NULL THEN 'GOOD' 
                       ELSE CASE WHEN GradeII IS NOT NULL THEN 'Excellent' 
                       ELSE '' END 
                       END
FROM #employee

答案 1 :(得分:1)

尝试这样

SELECT ID,Description,
       CASE WHEN GRADE1 IS NOT NULL THEN 'Excellent'
            WHEN GRADE2 IS NOT NULL THEN 'Good'
            WHEN GRADE1 IS NULL AND GRADE2 IS NULL THEN 'AVERAGE'
            ELSE ' '
       END [GRADE]
FROM TABLE1

请看一下

CASE