Ini akan berhasil:
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;
Pengembalian:
ct_total
:jumlah totalb
pera
.ct_distinct_b
:jumlahb
. yang berbeda pera
.b_arr
:larikb
ditambah frekuensib
, diurutkan berdasarkan frekuensib
.
Diurutkan berdasarkan jumlah total b
per a
.
Atau, Anda dapat menggunakan ORDER BY
klausa dalam panggilan agregat
di PostgreSQL 9.0 atau lebih baru. Seperti:
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;
Mungkin lebih jelas. Tapi biasanya lebih lambat. Dan pengurutan baris dalam subkueri berfungsi untuk kueri sederhana seperti ini. Penjelasan lebih lanjut: