我有一个场景,我需要选择员工的最新ID。 id可以是varchar或int
id mail
-------------
1234 xyz@abc.com
5678 xyz@abc.com
C123 xyz@abc.com
C234 def@abc.com
现在,我的查询结果必须是
id mail
-------------
5678 xyz@abc.com
C234 def@abc.com
逻辑是,如果对邮件ID有一个整数,则必须选择最高整数。如果没有整数,则可以选择varchar值。
尝试
select max(id), mail from worker group by mail
但是当邮件ID重复时,它会选择varchar值。
答案 0 :(得分:2)
我会使用isnumeric值和ROW_NUMBER来选择正确的值。
DECLARE @T TABLE (id VARCHAR(10), mail VARCHAR(100))
INSERT @T VALUES
('1234', 'xyz@abc.com'),
('5678', 'xyz@abc.com'),
('C123', 'xyz@abc.com'),
('C234', 'def@abc.com')
SELECT id, mail
FROM (
SELECT
id,
mail,
ROW_NUMBER() OVER (
PARTITION BY
mail
ORDER BY
CASE WHEN ISNUMERIC(id) = 1 THEN CONVERT(INT, id) ELSE 0 END DESC,
id) AS RowNum
FROM @T
) T
WHERE RowNum = 1
输出产量
id mail
---------- -------------
C234 def@abc.com
5678 xyz@abc.com
答案 1 :(得分:0)
我能想到的一个解决方案是:
select MAX(t.id), t.email
from (
select * from Emails where ISNUMERIC(id) = 1
union
select * from Emails where ISNUMERIC(id) <> 1 and email not in
(select email from Emails where ISNUMERIC(id) = 1)
) as t
group by t.email