我想生成userID,逻辑是,UserID是FirstName和LastName的组合。如果userID已存在,则在FirstName和LastName之后添加1。
代表:
用户John Doe的用户ID将是John Doe。
如果另一个John Doe加入公司,那么UserID应该是JohnDoe1,依此类推。
我用来实现这个目的的案例陈述如下。
Select distinct case
when lower(a.First_Name) || lower(a.Last_Name) = b.Name then a.First_Name || a.Last_Name || 1
when lower(a.First_Name) || lower(a.Last_Name) || 1 = b.Name then a.First_Name || a.Last_Name || 2
else a.first_name || a.last_name
end as user_id from Users a, accounts b
where a.unique_id = '12345' (This is matching key from table B)
在我的表中,我已经有了userID JohnDoe和JohnDoe1。
和输出我得到的以上查询是,
JOHNDOE JohnDoe1 JohnDoe2
我如何仅将JohnDoe2作为输出。
答案 0 :(得分:0)
这是一个可能适用于Oracle的解决方案:
WITH oldnames AS (
SELECT 'JohnDoe' AS user_id, 'John' AS fname, 'Doe' AS lname
FROM dual
UNION
SELECT 'JohnDoe1' AS user_id, 'John' AS fname, 'Doe' AS lname FROM dual
UNION
SELECT 'MaxHeadroom' AS user_id, 'Max' AS fname, 'Headroom' AS lname FROM dual
), newnames AS (
SELECT 'John' AS fname, 'Doe' AS lname FROM dual
UNION
SELECT 'Max' AS fname, 'Headroom' AS lname FROM dual
UNION
SELECT 'Mark' AS fname, 'Twain' AS lname FROM dual
)
SELECT n1.fname, n1.lname, MAX(n2.user_id)
, n1.fname || n1.lname ||
CASE WHEN MAX(n2.user_id) IS NOT NULL THEN TO_CHAR(COALESCE(TO_NUMBER(MAX(REGEXP_SUBSTR(n2.user_id, '\d+$'))), 0) + 1) END
FROM newnames n1, oldnames n2
WHERE n1.fname = n2.fname(+)
AND n1.lname = n2.lname(+)
GROUP BY n1.fname, n1.lname
我假设您有一张表,您可以在其中存储用户ID以及名字和姓氏。我在上面的查询中称之为oldnames
,newnames
是您要为其生成ID的用户表。