我正在尝试在TSQL中返回结果,其中 仅 显示有多个名称的地址。棘手的部分是这个表中已经有多个重复...所以我尝试过的Count Count变量不起作用,因为它们都有一个大于一的计数。所以我无法轻易区分具有相同地址的唯一名称。下面说明的解决方案就是我想要制作的...我有,但我的解决方案是在Access中最后一次失败的努力,我最终使用带有三个子查询的查询来获得结果:
Address Name
101 1st Ave Brian Wood
101 1st Ave Amy Wood
101 1st Ave Adam Wood
555 5th St Sarah Parker
555 5th St Parker Corp.
示例数据看起来像这样:
Address Name
101 1st Ave Brian Wood
101 1st Ave Brian Wood
101 1st Ave Brian Wood
101 1st Ave Amy Wood
101 1st Ave Adam Wood
555 5th St Sarah Parker
555 5th St Sarah Parker
555 5th St Sarah Parker
555 5th St Parker Corp.
我一直试图让这个问题持续数小时......我知道他们这样做的方式要简单得多,但是因为这是一个16小时的一天而且它是2点我能不能理解它。
以下是我最好的TSQL结果示例...它可以解决这个问题,但它会将其变成两个不同的列:
SELECT DISTINCT t1.Name, t2.Name, t1.Address
FROM tblLeads t1
JOIN tblLeads t2 ON t1.Address = t2.Address
WHERE t1.Name <> t2.Name
ORDER BY t1.Address
答案 0 :(得分:5)
您可以使用GROUP
COUNT(Distinct Name) > 1
来获取包含1个以上唯一名称的地址,然后在上述分组地址中使用过滤器选择不同的颜色。
SELECT DISTINCT Address,Name
From Table1
WHERE Address IN (
SELECT Address
FROM Table1
GROUP BY Address
HAVING COUNT(distinct Name) > 1
)
答案 1 :(得分:5)
您可以使用多个CTE's
来简化此任务。您首先要清理数据,因此请删除所有这些重复数据,因此您可以使用DISTINCT
。然后使用Count(*)OVER(Partition By Address)
获取每Address
行的计数:
WITH CleanedData AS
(
SELECT DISTINCT Address, Name
FROM dbo.tblLeads
),
CTE AS
(
SELECT Address, Name,
cnt = Count(*) OVER (Partition By Address)
FROM CleanedData
)
SELECT Address, Name
FROM CTE
WHERE cnt > 1
答案 2 :(得分:2)
使用EXISTS
验证相同的地址,但使用其他名称:
SELECT DISTINCT t1.LastName, t1.Street
FROM tblLeads t1
WHERE EXISTS (select 1 from tblLeads t2
where t1.Street = t2.Street
and t1.LastName <> t2.LastName)
ORDER BY t1.Street
答案 3 :(得分:0)
select address, name
from (select t.*, count(*) over(partition by address) as cnt
from (select distinct address, name from tblLeads) t
) where cnt > 1