简体   繁体   English

SQL COUNT(*) 与 GROUP BY 和最后一行与总计数

[英]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.我想在一个组上使用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.我已经使用UNION在单独的子查询中运行没有GROUP BYCOUNT(*)来给出总计数,但这种方法似乎效率低下。 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 . DB2 支持GROUPING SETS Assuming no PCUST values are NULL and it is a string, the simplest method is:假设没有PCUST值是NULL并且它是一个字符串,最简单的方法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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