我有一个包含以下列的表:
a|b|c|d|e
我希望选择所有记录,以便重复列的子集组合(例如,a,b,c)。例如:
a|b|c|d|e
1|2|3|1|2
6|7|8|9|1
1|2|3|4|5
1|2|2|5|4
应该导致:
1|2|3|1|2
1|2|3|4|5
答案 0 :(得分:4)
这样做:
SELECT a,b,c,d,e
FROM t t1
WHERE EXISTS ( SELECT NULL
FROM t t2
WHERE t1.a = t2.a AND t1.b = t2.b AND t1.c = t2.c
AND t1.rowid <> t2.rowid
)
第二种方式(SQLite不支持(x,y) in (select two columns)
):
SELECT a,b,c,d,e
FROM t
WHERE quote(a)||','||quote(b)||','||quote(c)
IN ( SELECT quote(a)||','||quote(b)||','||quote(c)
FROM t
GROUP BY a,b,c
HAVING COUNT(*) > 1
)
第三种方式:
SELECT a,b,c,d,e
FROM ( SELECT a,b,c
FROM t
GROUP BY a,b,c
HAVING COUNT(*) > 1
)
NATURAL JOIN t
最后一个有一个优点,你也可以添加聚合行(就像你在其他RDBMS中使用分析函数一样:)
sqlite> .headers on
sqlite> .mode column
sqlite> .width 3 3 3 3 3 20
sqlite> SELECT a,b,c,d,e,"Rows in this group"
...> FROM ( SELECT a,b,c
...> , COUNT(*) AS "Rows in this group"
...> FROM t
...> GROUP BY a,b,c
...> HAVING COUNT(*) > 1
...> )
...> NATURAL JOIN t;
a b c d e Rows in this group
--- --- --- --- --- --------------------
1 2 3 1 2 2
1 2 3 4 5 2
与Oracle中的相似:
WITH x AS
(SELECT a,b,c,d,e,COUNT(*) OVER (PARTITION BY a,b,c) "Rows in this group"
FROM t
)
SELECT * FROM x WHERE "Rows in this group" >= 2