1

我正在使用 SSMS 2008 并尝试使用 HAVING 语句。这应该是一个真正简单的查询。但是,尽管有许多重复项,但我只收到一个记录返回事件。

我在这里的 HAVING 语句做错了吗?或者还有其他我可以使用的功能吗?

select
      address_desc,
      people_id
from 
      dbo.address_view
where people_id is not NULL
group by people_id , address_desc
having count(*) > 1

来自 address_view 的样本数据:

people_id                            address_desc
----------                           ------------
Murfreesboro, TN  37130          F15D1135-9947-4F66-B778-00E43EC44B9E
11 Mohawk Rd., Burlington, MA 01803 C561918F-C2E9-4507-BD7C-00FB688D2D6E
Unknown, UN  00000                    C561918F-C2E9-4507-BD7C-00FB688D2D6E
Jacksonville, NC  28546          FC7C78CD-8AEA-4C8E-B93D-010BF8E4176D
Memphis, TN  38133                    8ED8C601-5D35-4EB7-9217-012905D6E9F1
44 Maverick St., Fitchburg, MA  8ED8C601-5D35-4EB7-9217-012905D6E9F1
4

2 回答 2

2

GROUP BY 会将您的重复项集中到一行中。

我认为相反,您希望找到所有people_id具有重复的值address_desc

SELECT a.address_desc, a.people_id
    FROM dbo.address_view a
        INNER JOIN (SELECT address_desc
                        FROM dbo.address_view
                        GROUP BY address_desc
                        HAVING COUNT(*) > 1) t
            ON a.address_desc = t.address_desc
于 2011-10-04T20:56:41.027 回答
0

使用 row_number 和 partition 您可以找到 row_num>1 的重复出现

select address_desc,
people_id,
row_num
from
(
select
  address_desc,
  people_id,
  row_number() over (partition by address_desc order by address_desc) row_num
from 
  dbo.address_view
where people_id is not NULL

) x 其中 row_num>1

于 2021-07-23T16:20:22.553 回答