我在表格中有一个PromoID字段。我需要弄清楚如何显示前6个字符相同的所有记录:
PromoID
=======
100001
100001A
100001B
101001
100002
100002A
我希望从上面看到的结果是:
PromoID
=======
100001
100001A
100001B
100002
100002A
101001被删除,因为它没有另一个带有“101001”前缀的记录。
由于
答案 0 :(得分:8)
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 ║
╚═════════╝
Here is一个带有演示的方形小说。
答案 1 :(得分:6)
如果您使用的是SQL Server 2005或更高版本,这应该对您有用:
SELECT PromoID
FROM (
SELECT *, COUNT(*) OVER (PARTITION BY LEFT(PromoID, 6)) AS cnt
FROM atable
) s
WHERE cnt > 1
;
您也可以尝试此at SQL Fiddle。
答案 2 :(得分:1)
您也可以使用子选择
来执行此操作SELECT PromoID FROM YourTable
WHERE LEFT(PromoID,6) IN
(
SELECT LEFT(PromoID,6)
FROM YourTable
Group By LEFT(PromoID, 6)
HAVING COUNT(*) > 1
)
答案 3 :(得分:0)
您可以使用公用表表达式执行此操作:
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;
答案 4 :(得分:0)
内部查询列出要拒绝的所有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
)