SQL删除某些重复的值

时间:2015-03-04 20:27:08

标签: sql vertica

我有一个这样的结果表(在运行查询之后):

     id     |  time  | region
12x-4nm-334 | 16:00  | Utah
12x-4nm-334 | 17:00  | California
12x-4nm-334 | 19:00  | Missouri
12x-4nm-334 | 22:00  | California
983-n2n-aq2 |  8:00  | New York
983-n2n-aq2 |  9:00  | New York

此表中还有一些其他列,但重要的是我要删除仅从结果中注册到一个区域的ID。所以像" 983-n2n-aq2"只显示在单个区域(不论时间)不应出现在结果表中。

希望这个问题足够清楚。

4 个答案:

答案 0 :(得分:1)

如果您使用MySql

    DELETE FROM table 
    WHERE id IN (   SELECT x.id
                    FROM (  select *
                            FROM table t
                            GROUP BY id
                            HAVING COUNT(DISTINCT region) = 1
                           ) as x
                    )

我不知道Vertica。希望有所帮助

答案 1 :(得分:0)

试试这个:

SELECT id, count(DISTINCT region) as RegionCount
FROM table
GROUP BY
    id
HAVING count(DISTINCT region) > 1

如果您的DBMS不支持count(distinct ),那么应该这样做:

SELECT id, count(DISTINCT region) as RegionCount
FROM (
    SELECT id, region FROM table GROUP BY id, region
) as table
GROUP BY
    id
HAVING count(DISTINCT region) > 1

答案 2 :(得分:0)

试试这个(借用Geerkens先生):

SELECT a.*
FROM table a INNER JOIN
(
    SELECT id
    FROM table
    GROUP BY id
    HAVING count(DISTINCT region) > 1
) b ON a.id = b.id

答案 3 :(得分:0)

首先获取具有多个不同区域的ID(如子查询中所示),然后在WHERE子句中使用它进行过滤。

SELECT id, time, region
FROM mytable
WHERE id IN
(
    SELECT id
    FROM mytable
    GROUP BY id
    HAVING count(DISTINCT region) > 1
)