添加两个选择计数查询的总和

时间:2015-10-28 14:43:45

标签: sql sql-server

我正在使用SQL Server 2012。

我有两个表,我正在尝试查看两个表包含多少行。他们没有可以加入的共同领域。以下是我目前的查询,显然不起作用。怎么会这样?

;with tblOne as
(
    select count(*) numRows from tblOne where DateEx = '2015-10-27'
),
tblTwo as
(
    select count(*) numRows from tblTwo where Status = 0
)
select tblOne.numRows + tblTwo.numRows

3 个答案:

答案 0 :(得分:6)

您不需要CTE;您可以将它们更改为子查询:

select 
    (select count(*) numRows from tblOne where DateEx = '2015-10-27') +   
    (select count(*) numRows from tblTwo where Status = 0)

如果您真的想要使用CTE,那么只需执行隐式CROSS JOIN:

with tblOne as
(
    select count(*) numRows from tblOne where DateEx = '2015-10-27'
),
tblTwo as
(
    select count(*) numRows from tblTwo where Status = 0
)
select tblOne.numRows + tblTwo.numRows
FROM tblOne, tblTwo

答案 1 :(得分:2)

您可以使用cross join

with tblOne as (
      select count(*) as numRows from tblOne where DateEx = '2015-10-27'
     ),
     tblTwo as (
      select count(*) as numRows from tblTwo where Status = 0
     )
select tblOne.numRows + tblTwo.numRows
from tblOne cross join tblTwo;

答案 2 :(得分:2)

使用联合和查询

select sum(numRows) as numRows from (
    select count(*) numRows from tblOne where DateEx = '2015-10-27'
    union all
    select count(*) numRows from tblTwo where Status = 0
)

编辑:添加了union all,所以如果两个查询都有相同的行数,则会包含两个结果。