これでうまくいくはずです:
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;
返品:
-
ct_total:bの総数aごと 。 -
ct_distinct_b:個別のbの数aごと 。 -
b_arr:bの配列 プラスbの頻度 、bの頻度で並べ替え 。
bの総数で並べ替え aごと 。
または、 ORDER BYを使用することもできます。 集約呼び出し内の句
PostgreSQL9.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; より明確になる可能性があります。しかし、通常は遅くなります。また、サブクエリの行の並べ替えは、このような単純なクエリで機能します。詳細説明: