我有Table1,它有一个名为员工编号的列,我想根据具体范围对其进行分类 例如:
id employeeNumber
1 0
1 50
2 100
3 500
4 1000
我希望结果是这样的,例如,如果有多少员工来自 0到100它会落在C1中, 500到1000将落在C2 ..等等
1 C1
1 C1
2 C1
3 C2
4 C2
答案 0 :(得分:2)
您可以使用case
:
select t1.id,
(case when employeenumber between 0 and 100 then 'C1'
when employeenumber between 500 and 1000 then 'C2'
end) as en_range
from table1 t1;
您似乎没有101-499的范围。
答案 1 :(得分:2)
使用像
这样的CASE语句SELECT
CASE
WHEN employeeNumber BETWEEN 0 AND 100 THEN 'C1'
WHEN employeeNumber BETWEEN 101 AND 500 THEN 'C2'
END as employeeCode FROM table
答案 2 :(得分:2)
有几种方法可以做到这一点,这取决于您想要使用相同分组的频率。如果这是一次性的,我建议这样的事情(我不确定你的类别似乎不是连续的):
SELECT
id,
case
when employeeNumber <= 100 then 'C1'
when employeeNumber <= 500 then 'C2'
/* etc, the first match will be used so no need to worry about missing '>='s */
else 'Uncategorized' -- or if your final category has no upper limit, you could put that here, but be careful of `NULL`s as employeeNumber seems not to be a primary key field.
end as Category
FROM
Table1
如果要重复使用这些类别,请按如下方式创建表:
create table EmployeeCategories(
Category varchar(3), --Or whatever data type you need. You could also add extra columns to describe the category if that's helpful.
LowerBound int,
UpperBound int
)
用您的分组填充它:
insert into EmployeeCategories
(Category, LowerBound, UpperBound)
values ('C1', 0, 100),
('C2', 101, 1000)
/* Etc */
对于最终类别,如果没有最大值,您可以离开UpperBound NULL
。然后你这样做:
SELECT
t.id,
ec.Category
FROM
Table1 t
CROSS JOIN EmployeeCategories ec
WHERE
t.employeeNumber between ec.LowerBound and ec.UpperBound
OR (t.employeeNumber >= ec.LowerBound and ec.UpperBound is null)