2014-10-30 75 views
0

我有一個場景,我需要選擇員工的最新ID。該ID可以是一個varchar或INT按列名分組的SELECT distinct行

id  mail 
------------- 
1234 [email protected] 
5678 [email protected] 
C123 [email protected] 
C234 [email protected] 

現在,我的查詢結果只是必須有

id  mail 
------------- 
5678 [email protected] 
C234 [email protected] 

的邏輯是,如果沒有針對郵件ID的整數,最高整數必須被挑選。如果沒有整數,則可以選取varchar值。

試圖

select max(id), mail from worker group by mail 

但如果有重複的郵件ID則會選取VARCHAR值。

+1

你有任何其他列則可以按確定的最新,就像插入日期? – 2014-10-30 12:47:37

回答

2

我會使用isnumeric值和ROW_NUMBER來選擇正確的值。

DECLARE @T TABLE (id VARCHAR(10), mail VARCHAR(100)) 
INSERT @T VALUES 
    ('1234', '[email protected]'), 
    ('5678', '[email protected]'), 
    ('C123', '[email protected]'), 
    ('C234', '[email protected]') 

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  [email protected] 
5678  [email protected] 
+0

是的。這對我來說工作得很好。謝謝 :) – mhn 2014-10-31 09:08:24

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