Click here to Skip to main content
15,916,280 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
how to find count over rows selected by union .

My sql Query is:
SQL
select Table1.ID,Table1.RollNo
from 
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where Table1.Subject='Maths' and Table2.Category='Complusary'
union
select Table1.ID,Table1.RollNo
from
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where Table1.Subject='Maths' and Table2.Category='Elective'


It reurns two rows i want output like
Count
2
Posted
Updated 31-Jul-12 0:53am
v3

SQL
with Cte_Test as 
select Table1.ID,Table1.RollNo
from
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where Table1.Subject='Maths' and Table2.Category='Complusary'
union
select Table1.ID,Table1.RollNo
from
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where Table1.Subject='Maths' and Table2.Category='Elective')
select count(1) from cte_test


or something like this

SQL
Select count(1) from (select Table1.ID,Table1.RollNo
from
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where Table1.Subject='Maths' and Table2.Category='Complusary'
union
select Table1.ID,Table1.RollNo
from
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where Table1.Subject='Maths' and Table2.Category='Elective')as  A
 
Share this answer
 
v2
Try it as follows

SQL
Select count(*) from (
select Table1.ID,Table1.RollNo
from 
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where Table1.Subject='Maths' and Table2.Category='Complusary'
union
select Table1.ID,Table1.RollNo
from
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where Table1.Subject='Maths' and Table2.Category='Elective') as test


Regards
Sebastian
 
Share this answer
 
Actually there are no need to use Union first of all try this.
SQL
select Table1.ID,Table1.RollNo
from
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where (Table1.Subject='Maths' and (Table2.Category='Complusary' or Table2.Category='Elective')



and also this
SQL
select Table1.ID,Table1.RollNo
from
Table1 inner join Table2 on Table1.RollNo = Table2.RollNo and Table1.ID = Table2.ID
where Table1.Subject='Maths' and Table2.Category in ('Complusary','Elective')
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900