我正在寻找编写此查询的PostgreSQL版本的优雅方式:
SELECT count(distinct a,b) / count(distinct c,d)
FROM t1
GROUP BY e;
它可以通过CONCAT功能完成,但在这种情况下我会获得巨大的性能下降。
每个计数不同都可以这样写:
SELECT count(*), e FROM
(SELECT a, b, e FROM t1 GROUP BY a, b, e) as tmp
GROUP BY e;
AND
SELECT count(*), e FROM
(SELECT c, d, e FROM t1 GROUP BY c, d, e) as tmp
GROUP BY e;
但我无法找到如何将它们组合成一个查询以获得最终结果
这是用于测试语法的create table:
CREATE TABLE t1 (
a int,
b int,
c int,
d int,
e int
);
答案 0 :(得分:1)
不确定优雅,但看起来可以这样做:
SELECT e, c1/c2 FROM
(SELECT count(*) as c1, e FROM
(SELECT a, b, e FROM t1 GROUP BY a, b, e) as sub1
GROUP BY e) as tmp1
INNER JOIN
(SELECT count(*) as c2, e FROM
(SELECT c, d, e FROM t1 GROUP BY c, d, e) as sub2
GROUP BY e) as tmp2
USING (e)