且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL中查找以相同字符串开头的行(相似的行)?

更新时间:2023-02-17 17:32:23

给出的第一个解决方案将标识键前缀;稍微扩展一下,以使表行以这些键开头:

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
)

或者,您可以在包含前缀的临时表和原始表之间使用联接-如果前缀的数量很大,则使用"where in"可能会变得非常昂贵.

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.