我在表中有一个 PromoID 字段。我需要弄清楚如何显示前 6 个字符相同的所有记录:
PromoID
=======
100001
100001A
100001B
101001
100002
100002A
我希望从上面看到的结果是:
PromoID
=======
100001
100001A
100001B
100002
100002A
101001 被删除,因为它没有另一个带有“101001”前缀的记录。
谢谢
SELECT PromoID
FROM YourTable A
WHERE EXISTS(SELECT LEFT(PromoID,6)
FROM YourTable
WHERE LEFT(PromoID,6) = LEFT(A.PromoID,6)
GROUP BY LEFT(PromoID,6)
HAVING COUNT(*) > 1)
这是结果:
╔═════════╗
║ PromoID ║
╠═════════╣
║ 100001 ║
║ 100001A ║
║ 100001B ║
║ 100002 ║
║ 100002A ║
╚═════════╝
这是一个带有演示的sqlfiddle。
如果您使用的是 SQL Server 2005 或更高版本,这应该适合您:
SELECT PromoID
FROM (
SELECT *, COUNT(*) OVER (PARTITION BY LEFT(PromoID, 6)) AS cnt
FROM atable
) s
WHERE cnt > 1
;
你也可以在 SQL Fiddle上试试这个。
您也可以使用子选择来执行此操作
SELECT PromoID FROM YourTable
WHERE LEFT(PromoID,6) IN
(
SELECT LEFT(PromoID,6)
FROM YourTable
Group By LEFT(PromoID, 6)
HAVING COUNT(*) > 1
)
您可以使用公用表表达式执行此操作:
WITH CTE (Prefix) AS
(select LEFT(PromoId, 6) from Foo GROUP BY LEFT(PromoId, 6) HAVING COUNT(1) > 1)
SELECT PromoId FROM Foo
INNER JOIN CTE ON LEFT(PromoId, 6) = CTE.Prefix;
内部查询列出了所有要拒绝的 PromoID。外部查询采用所有 PromoID 减去被拒绝的:
SELECT *
FROM table1
WHERE PromoID not in (
SELECT t1.PromoID
FROM table1 t1
LEFT JOIN table1 t2 ON t1.PromoID != t2.PromoID
AND left(t1.PromoID, 6) = left(t2.PromoID, 6)
WHERE t2.PromoID IS NULL
)