2010-11-02 67 views
3

我的情況是這樣的:T-SQL檢查重複字段1值,但不同FIELD2值

我有一個表,像這樣的結構(簡體) -

CREATE TABLE [dbo].[pe_mem](
    [pm_member] [int] NULL, 
    [pm_surname] [char](50) NULL, 
    [pm_forename] [char](50) NULL, 
    [pm_rsi_num] [char](11) NULL 

) ON [PRIMARY] 

我需要運行一個查詢找到所有具有相同 pm_rsi_num但不同 pm_surname的行。

任何人都可以幫我解決這個問題嗎?

謝謝!

回答

2

已存在的變體:

select * 
from pe_mem t1 
where exists 
(select null 
from pe_mem t2 
where t1.pm_rsi_num = t2.pm_rsi_num 
     and t1.pm_surname <> t2.pm_surname) 

單表掃描版本:

select pm_rsi_num 
from pe_mem 
group by pm_rsi_num 
having count(distinct pm_surname) > 1 
4

您可以使用自聯接爲:

select * 
from pe_mem t1 
join pe_mem t2 
on  t1.pm_rsi_num = t2.pm_rsi_num 
     and t1.pm_surname <> t2.pm_surname 
2

剛剛加入表背本身和使用標準作爲連接標準:

select * from pe_mem as p1 
inner join pe_mem as p2 
on p1.pm_rsi_num = p2.pm_rsi_num 
    and p1.pm_surname <> p2.pm_surname