如何在select语句中分类

时间:2011-04-17 13:21:28

标签: sql

我有一个表(在Oracle数据库中),如下所示:

department
----------
Finance
Sales
Programmer
Network Admin
System Support

我希望输出看起来像下表:

department
----------
Finance
Sales
IT (those category other than Finance and Sales will group under 'IT')

这可能吗?

2 个答案:

答案 0 :(得分:4)

SELECT DISTINCT
CASE
    WHEN department IN ('Programmer', 'Network Admin', 'System Support') THEN 'IT'
    ELSE department
END
FROM yourTable

答案 1 :(得分:1)

您应该在客户端代码中执行此操作,而不是在数据库级别执行此操作。

但是,如果有一个包含映射的附加表,则可能:

INSERT INTO mappings (department, mapping) VALUES ('Programmer', 'IT');
INSERT INTO mappings (department, mapping) VALUES ('Admin', 'IT');
INSERT INTO mappings (department, mapping) VALUES ('Support', 'IT');

SELECT t.*, COALESCE(m.mapping, t.department) FROM table t
LEFT JOIN mappings m ON (m.department = t.department)