我的情况是:
我有一个像这样(简化)结构的表 -
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的所有行。
任何人都可以帮我解决这个问题吗?
谢谢!
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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