结合多种策略来生成一个独特的列?
Combine multiple strategies to generate a unique column?
我有一名员工 table,有 last_name 和 first_name 列。我想生成一个名为 employee_code 的列,它将始终包含 3 个字符并且是唯一的。如果尚不存在,代码将是 first_name 的第一个字母,后跟两个姓氏的第一个字母。
SELECT 'LUDOVIC' AS first_name, 'AUBERT' AS last_name, 'LAU' AS employee_code;
但是如果 'LAU' 已经存在,我想使用替代策略,例如使用名字的两个首字母后跟姓氏的首字母。
SELECT 'LUDOVIC' AS first_name, 'AUBERT' AS last_name, 'LUA' AS employee_code;
如何在 SQL 中实现这一点?
DROP TABLE IF EXISTS employe;
CREATE TABLE employe (
id int primary key,
first_name varchar(30),
last_name varchar(30),
code1 char(3),
nb1 int NULL,
code2 char(3),
code char(3) NULL
);
insert into employe (id, first_name, last_name, code1, code2)
VALUES (1,'LUDOVIC','AUBERT','LAU','LUA'),(2,'LUDOVICO','AUBERT','LAU','LUA');
SELECT * FROM employe;
WITH cte AS (
SELECT id, first_name, last_name, code1, rank() OVER (PARTITION BY code1 ORDER BY id ASC) as n1, code2
FROM employe
)
SELECT *, CASE WHEN n1=1 THEN code1 ELSE code2 END AS code FROM cte;
我有一名员工 table,有 last_name 和 first_name 列。我想生成一个名为 employee_code 的列,它将始终包含 3 个字符并且是唯一的。如果尚不存在,代码将是 first_name 的第一个字母,后跟两个姓氏的第一个字母。
SELECT 'LUDOVIC' AS first_name, 'AUBERT' AS last_name, 'LAU' AS employee_code;
但是如果 'LAU' 已经存在,我想使用替代策略,例如使用名字的两个首字母后跟姓氏的首字母。
SELECT 'LUDOVIC' AS first_name, 'AUBERT' AS last_name, 'LUA' AS employee_code;
如何在 SQL 中实现这一点?
DROP TABLE IF EXISTS employe;
CREATE TABLE employe (
id int primary key,
first_name varchar(30),
last_name varchar(30),
code1 char(3),
nb1 int NULL,
code2 char(3),
code char(3) NULL
);
insert into employe (id, first_name, last_name, code1, code2)
VALUES (1,'LUDOVIC','AUBERT','LAU','LUA'),(2,'LUDOVICO','AUBERT','LAU','LUA');
SELECT * FROM employe;
WITH cte AS (
SELECT id, first_name, last_name, code1, rank() OVER (PARTITION BY code1 ORDER BY id ASC) as n1, code2
FROM employe
)
SELECT *, CASE WHEN n1=1 THEN code1 ELSE code2 END AS code FROM cte;