0

I'm using SQL Server 2012.

I have two tables and I'm trying to see how many rows both tables contain. They have no common field on which they can join. Below is my query so far, which obviously doesn't work. How should it be?

;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
1
  • 2
    SELECT t1.numRows + t2.numRows FROM tblOne t1 CROSS JOIN tblTwo t2 Commented Oct 28, 2015 at 14:45

3 Answers 3

6

You don't need CTEs; you can just change them to subqueries:

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

If you REALLY want to use CTEs then just do an implicit 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
Sign up to request clarification or add additional context in comments.

2 Comments

May I ask why an implicit CROSS JOIN instead of an explicit one?
@Lamak No strong reason - just a shorter syntax, and no concern about cartesian product issues since each subquery is only one record. I prefer the subqueries to be honest.
2

You can use a 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;

Comments

2

Use union and query from that

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
)

edit: Added union all, so if it happens that both queries have same amount of rows the both results are included.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.