How to find rows in SQL that start with the same string (similar rows)?

家住魔仙堡 提交于 2019-12-12 04:09:29

问题


I have a table with primary keys that look like this:

FIRSTKEY~ABC

SECONDKEY~DEF

FIRSTKEY~DEF

I want to write a SELECT statement that strips off the segment following the tilde and returns all rows that are duplicates after the post-tilde segment is gone. That is,

SELECT ...

Gives me:

FIRSTKEY~ABC

FIRSTKEY~DEF

As "duplicates".

I already have the bit to strip off the end segment using SUBSTRING:

SELECT SUBSTRING(COLUMN, 0, CHARINDEX('~', COLUMN)) FROM TABLE

This is on SQL Server.


回答1:


The first solution given will identify the key prefixes; extend it just a bit to get the table rows beginning with those keys:

SELECT * 
FROM TABLE
WHERE SUBSTRING(COLUMN, 0, CHARINDEX('~', COLUMN)) IN
(
    SELECT SUBSTRING(COLUMN, 0, CHARINDEX('~', COLUMN)) FROM TABLE 
    GROUP BY SUBSTRING(COLUMN, 0, CHARINDEX('~', COLUMN))
    HAVING COUNT(*) > 1
)

Alternately, you could use a join between a temp table containing the prefixes and the original table - if the number of prefixes becomes very large, using a "where in" can become very expensive.




回答2:


Give this a shot

SELECT SUBSTRING(COLUMN, 0, CHARINDEX('~', COLUMN)), COUNT(*) FROM TABLE 
GROUP BY SUBSTRING(COLUMN, 0, CHARINDEX('~', COLUMN))
HAVING COUNT(*) > 1


来源:https://stackoverflow.com/questions/3289900/how-to-find-rows-in-sql-that-start-with-the-same-string-similar-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!