查询以返回具有某些条件的附加列

时间:2011-10-13 06:28:48

标签: sql sql-server tsql

表:Emaployee
列:name(nvarchar(256)),Salary(decimal(18,2))

现在,我希望结果有附加列
'Grade'=
'A'如果工资<15000.00,
'B'如果25000.00&gt;工资&gt; 15000.00,
'C'如果工资> 25000.00

如何为此编写查询?

3 个答案:

答案 0 :(得分:3)

SELECT name, 
       salary, 
       (CASE 
             WHEN salary<15000 THEN 'A' 
             WHEN salary>15000 AND salary <25000 THEN 'B' 
             ELSE 'C' 
       END) AS grade
FROM employee

没有尝试过以下但也可能有效:

SELECT name, 
       salary, 
       IIF (salary<15000, 'A', IIF (salary>15000 AND salary<25000, 'B', IIF (salary>25000, 'C', ))) AS grade
FROM employee

答案 1 :(得分:2)

使用Denali将IIF引入T-SQL,因此最新版只适用于Denali版本 请查看此T-SQL IIF function tutorial

答案 2 :(得分:2)

  

'等级'=       如果工资<15000.00,'A',       'B'如果25000.00&gt;薪水&gt; 15000.00,       'C'如果工资> 25000.00

该规格似乎有缺陷。您需要回到您的设计师那里,询问他们哪个等级适用于薪水恰好为15000.00和25000.00的员工,因为这些未被指定。以下是猜测(我不建议在实践中猜测):

SELECT name, salary, 'A' AS Grade
  FROM Employee
 WHERE Salary BETWEEN 0 AND 14999.99
UNION
SELECT name, salary, 'B' AS Grade
  FROM Employee
 WHERE Salary BETWEEN 15000.00 AND 24999.99
UNION
SELECT name, salary, 'C' AS Grade
  FROM Employee
 WHERE Salary >= 25000.00;