Если ваша СУБД поддерживает window functions (analytic functions)
, то вы можете использовать это:
SELECT
SUM(COUNT(*)) OVER (PARTITION BY cust_ref) AS cnt,
cust_ref, account_num,
MAX(phone_num) AS max_phone_num
FROM table_name
GROUP BY cust_ref, account_num
ORDER BY 1 DESC, 2, 3; --cnt DESC, cust_ref, account_num
Протестировано в rextester for Oracle
Если вы хотите сделать заказ в каждой группетоже cust_ref, account_num
, затем используйте это:
SELECT
SUM(COUNT(*)) OVER (PARTITION BY cust_ref) AS cnt,
COUNT(*) AS cnt_in_group,
cust_ref, account_num,
MAX(phone_num) AS max_phone_num
FROM table_name
GROUP BY cust_ref, account_num
ORDER BY cnt DESC, cnt_in_group DESC, cust_ref, account_num;
Ссылка rextester