简体   繁体   中英

SQL COUNT(*) with GROUP BY and a final row with the total count

I want to use COUNT(*) on a group and then one more row at the end to give the full count. I have used UNION to run the COUNT(*) without GROUP BY in a separate sub-query to give the total count, but that approach seems inefficient. Any ways to combine both?

SELECT PCUST, COUNT(*) FROM PAYMENT 
WHERE PAYMENT_DATE = '2020-12-30'
GROUP BY PCUST
UNION
SELECT 'TOTAL', COUNT(*) FROM PAYMENT
WHERE PAYMENT_DATE = '2020-12-30'

As you can see from above query, I am repeating the same condition to get the partial and total counts. Plz suggest any way to optimize this.

DB2 supports GROUPING SETS . Assuming no PCUST values are NULL and it is a string, the simplest method is:

SELECT COALESCE(PCUST, 'TOTAL'), COUNT(*)
FROM PAYMENT 
WHERE PAYMENT_DATE = '2020-12-30'
GROUP BY GROUPING_SETS ( (PCUST), () )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM