HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Sum up counts in subquery

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
subquerycountssum

Problem

I am writing a query to check if I have got duplicates in a certain column.

SELECT COUNT(thecol) FROM thetable WHERE thecol IS NOT NULL GROUP BY thecol 
  HAVING COUNT(*) > 1


That will give me an output like

3
5
6


Which of course is the number of records for each value of thecol where thecol is not unique.

Now how do I only get the sum 14? Should I have the existing query as a subquery?

Solution

Does this do what you want?

SELECT 
    total = 
        SUM(x.records)
FROM 
(
    SELECT 
        records = 
            COUNT_BIG(thecol)
    FROM thetable 
    WHERE thecol IS NOT NULL 
    GROUP BY thecol 
    HAVING COUNT(*) > 1
) AS x;

Code Snippets

SELECT 
    total = 
        SUM(x.records)
FROM 
(
    SELECT 
        records = 
            COUNT_BIG(thecol)
    FROM thetable 
    WHERE thecol IS NOT NULL 
    GROUP BY thecol 
    HAVING COUNT(*) > 1
) AS x;

Context

StackExchange Database Administrators Q#228953, answer score: 10

Revisions (0)

No revisions yet.