Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two SELECT statements from same table with diff. where condition

Tags:

sql

Suppose we have an Emp table with EmpId, Manager, Subb as three columns.

Manager is 1 when EmpId is manager, similarly for subb.

Require number of manager and subb from table.

Can we combine these two queries into a single SELECT query? (want to scan table just once)

select count(*) as ManagerNumber from Emp where Manager=1
select count(*) as Subordinate  from Emp where Subb=1.
like image 536
Anand Gupta Avatar asked Dec 26 '22 17:12

Anand Gupta


1 Answers

You can do this:

SELECT 
  SUM(CASE WHEN Manager = 1 THEN 1 ELSE 0 END) AS ManagerNumber, 
  SUM(CASE WHEN subb = 1 THEN 1 ELSE 0 END) AS Subordinate 
FROM Emp 

And it is SQL ANSI standard, it will work in all RDBMS.

like image 80
Mahmoud Gamal Avatar answered Mar 16 '23 01:03

Mahmoud Gamal