我需要使用Last作为标准查找具有相同地址的所有行,但是,如果有人居住在同一地址并使用不同的姓氏,我也需要将其返回。
我的表格的简化版本
ID Last Addr
---- ---- -----
1 Smith 123 Fake St
2 Smith 123 Fake St
3 Fox 123 Fake St
4 Jones 111 Jones Rd
我试过了这个查询
SELECT *
FROM Table
WHERE Addr IN
(SELECT Addr
FROM Table AS T
GROUP BY Addr
HAVING COUNT(ID) > 1)
AND Last = 'Smith'
这会返回ID 1和2,但我还需要它返回ID 3,因为地址是相同的。我知道它没有返回,因为Last在我的WHERE语句中不匹配,但是,当我搜索并且需要知道同一地址的所有其他人时,我将只有Last,无论他们的姓名如何。
答案 0 :(得分:1)
您可以使用COUNT(*) OVER()
:
WITH CTE AS
(
SELECT *,
N = COUNT(*) OVER(PARTITION BY Addr)
FROM dbo.YourTable
)
SELECT *
FROM CTE A
WHERE N > 1
AND EXISTS(SELECT 1 FROM dbo.YourTable
WHERE Last = 'Smith'
AND Addr = A.Addr);
答案 1 :(得分:0)
你可以进行计数和分组,任何超过1的东西都是重复
select ID, Last, Addr, count(1) num from table group by ID, Last, Addr
答案 2 :(得分:0)
请尝试以下方法:
SELECT *
FROM Table AS t
WHERE EXISTS (SELECT 1
FROM Table
WHERE Addr = t.Addr AND Last = 'Smith');
这是一个正在运行的示例:
declare @Table table (ID int, [Last] nvarchar(50), Addr nvarchar(50));
insert into @Table values
(1, 'Smith', '123 Fake St'),
(2, 'Smith', '123 Fake St'),
(3, 'Fox', '123 Fake St'),
(4, 'Jones', '111 Jones Rd');
SELECT *
FROM @Table AS t
WHERE EXISTS (SELECT 1
FROM @Table
WHERE Addr = t.Addr AND Last = 'Smith');
/* Result
ID Last Addr
-- -------- -----------------------
1 Smith 123 Fake St
2 Smith 123 Fake St
3 Fox 123 Fake St
*/