【问题标题】:TSQL: group by Substring (Name) and retrieve ID in SELECTTSQL:按子字符串(名称)分组并在 SELECT 中检索 ID
【发布时间】:2019-11-19 16:14:53
【问题描述】:

我们将公司的数据存储在一个表中。为了消除重复行,我们需要使用以下标准来识别重复的公司数据集:如果 CompanyName、City 和邮政编码的前五个字母与其他记录的相同字段匹配,则它是重复的。我们稍后将删除重复项。我遇到的问题是我无法检索这些记录的 ID,因为我没有对 ID 上的记录进行分组。 我正在使用以下 SQL:

Select count(ID) as DupCount
       , SUBSTRING(Name,1,5) as Name
       , City
       , PostalCode 
from tblCompany 
group by SUBSTRING(Name,1,5)
         , City
         , PostalCode 
Having count(ID) > 1 
order by count(ID) desc 

如何检索这些记录的 ID?

【问题讨论】:

    标签: sql-server tsql substring


    【解决方案1】:

    你可以使用窗口函数:

    Select c.*
    from (select c.*,
                 count(*) over (partition by left(Name, 5), City, PostalCode) as cnt
          from tblCompany c
         ) c
    where cnt >= 2;
    

    这将返回带有 dups 的各个行。然后,您可以对此进行总结或对结果集做任何您想做的事情。

    【讨论】:

      【解决方案2】:

      使用group_concat() 以逗号分隔列表的形式获取 id:

      select 
        SUBSTRING(Name,1,5) as Name,
        City,
        PostalCode,
        count(ID) as counter, 
        group_concat(id order by id) as ids
      from tblCompany 
      group by SUBSTRING(Name,1,5), City, PostalCode 
      having count(ID) > 1 
      order by count(ID) desc
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-15
        • 2017-08-29
        • 1970-01-01
        • 1970-01-01
        • 2022-10-24
        • 1970-01-01
        • 1970-01-01
        • 2014-02-07
        相关资源
        最近更新 更多