在2个不同的表上选择COUNT语句的SUM

时间:2015-10-27 18:40:58

标签: tsql count sum sql-server-2014

我想从不同表上的2个COUNT语句中提取COUNT值。 我试过了:

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

我试过了:

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

我试过了:

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

我不知道还有什么可以尝试...

2 个答案:

答案 0 :(得分:2)

你没试过:

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

或者:

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

答案 1 :(得分:1)

您可以使用:

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

如果articlegroupsemails可以为空,那么您还应该使用COALESCE

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