这应该可以解决问题:
SELECT a
, sum(ab_ct)::int AS ct_total
, count(*)::int AS ct_distinct_b
, array_agg(b || ', ' || ab_ct::text) AS b_arr
FROM (
SELECT a, b, count(*) AS ab_ct
FROM tbl
GROUP BY a, b
ORDER BY a, ab_ct DESC, b -- append "b" to break ties in the count
) t
GROUP BY a
ORDER BY ct_total DESC;
Returns:
-
ct_total
: 总数b
per a
.
-
ct_distinct_b
:不同的计数b
per a
.
-
b_arr
: 数组b
加上频率b
,按频率排序b
.
按总数排序b
per a
.
或者,您可以使用ORDER BY聚合调用中的子句 https://www.postgresql.org/docs/current/functions-aggregate.html在 PostgreSQL 9.0 或更高版本中。喜欢:
SELECT a
, sum(ab_ct)::int AS ct_total
, count(*)::int AS ct_distinct_b
, array_agg(b || ', ' || ab_ct::text ORDER BY a, ab_ct DESC, b) AS b_arr
FROM (
SELECT a, b, count(*) AS ab_ct
FROM tbl
GROUP BY a, b
) t
GROUP BY a
ORDER BY ct_total DESC;
可能会更清楚。但通常速度较慢。对子查询中的行进行排序适用于像这样的简单查询。更多解释:
- 如何将 ORDER BY 和 LIMIT 与聚合函数结合应用? https://dba.stackexchange.com/a/213724/3684