How to SUM Grouped and Counted Field Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to SUM Grouped and Counted Field without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I need to Sum of Counted and Grouped columns. By the way I need to Where Clause for specific condition.

Here is my complicated query;

SELECT COUNT(id) AS Counted, State FROM Table1
GROUP BY State
HAVING State NOT IN (2,3)

UNION ALL

SELECT SUM(Say) AS SubSUM, State FROM (
    SELECT COUNT(b.id) AS SubCount, b.State FROM Table1 AS b
    GROUP BY b.State
    HAVING b.State IN (2,3)
) S GROUP BY S.State 

I just want to know how many rows I have which is State 2 and 3. I hope explained.

Answer

I think you can do what you want with conditional aggregation. Something like this:

SELECT COUNT(id) AS total,
       SUM(CASE WHEN State NOT IN (2, 3) THEN 1 ELSE 0 END),
       SUM(CASE WHEN State IN (2, 3) THEN 1 ELSE 0 END)
FROM Table1;
We are here to answer your question about How to SUM Grouped and Counted Field - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji