patternsqlModerate
Sum up counts in subquery
Viewed 0 times
subquerycountssum
Problem
I am writing a query to check if I have got duplicates in a certain column.
That will give me an output like
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?
SELECT COUNT(thecol) FROM thetable WHERE thecol IS NOT NULL GROUP BY thecol
HAVING COUNT(*) > 1That will give me an output like
3
5
6Which 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.