Adam
Adam

Reputation: 6122

Selecting SUM of COUNT statements on 2 different tables

I want to SUM the COUNT values from 2 COUNT statements on different tables. I tried:

SELECT(
SELECT COUNT(*) FROM articlegroups 
UNION 
SELECT COUNT(*) FROM emails
) 
as t

I tried:

SELECT(
SELECT COUNT(*) FROM articlegroups 
+
SELECT COUNT(*) FROM emails
) 
as t

I tried:

SELECT SUM(
SELECT COUNT(*) FROM articlegroups 
+
SELECT COUNT(*) FROM emails
) 
as t

I don't know what else to try...

Upvotes: 0

Views: 44

Answers (2)

Giorgos Betsos
Giorgos Betsos

Reputation: 72165

You can use:

SELECT (SELECT COUNT(*) FROM articlegroups) + 
       (SELECT COUNT(*) FROM emails) AS cnt

If either articlegroups or emails can be empty, then you should also use COALESCE:

SELECT COALESCE((SELECT COUNT(*) FROM articlegroups),0) + 
       COALESCE((SELECT COUNT(*) FROM emails),0) AS cnt

Upvotes: 1

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

You didn't try:

SELECT SUM(cnt) as cnt FROM
(
    SELECT COUNT(*) as cnt FROM articlegroups 
    UNION ALL
    SELECT COUNT(*) as cnt FROM emails
) t

Or:

SELECT (SELECT COUNT(*) FROM articlegroups) + 
       (SELECT COUNT(*) FROM emails)  as cnt

Upvotes: 2

Related Questions