Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform multiple queries into single row

Tags:

sql

reporting

I have a report that I would like to base on a single SQL statement. The problem is the data is based on several SQL statements. For example.

SELECT COUNT(*) as 'Cases Opened' 
FROM tblCases 
WHERE DateAssigned BETWEEN @StartDate AND @EndDate

SELECT COUNT(*) as 'Cases Closed' 
FROM tblCases 
WHERE ClosedDate BETWEEN @StartDate AND @EndDate

SELECT COUNT(*) as 'Tickets Issued' 
FROM tblTicket 
WHERE DateIssued BETWEEN @StartDate AND @EndDate

SELECT COUNT(*) as 'Warnings Issued' 
FROM tblWarning 
WHERE DateIssued BETWEEN @StartDate AND @EndDate

Is there a way to turn these four seperate SQL statements into a single SQL statement such that each result is listed as a column? For example ..

Cases Opened        Cases Closed       Tickets Issued        Warnings Issued
******************************************************************************
   256         |      165          |        56           |          165

EDIT I am using SQL Server and no there is no relationship between the tables.

like image 377
webworm Avatar asked Jul 01 '26 16:07

webworm


1 Answers

select 
 (
 SELECT COUNT(*)  
 FROM tblCases 
 WHERE DateAssigned BETWEEN @StartDate AND @EndDate
 ) as 'Cases Opened' ,
 (SELECT COUNT(*)  
 FROM tblCases 
 WHERE ClosedDate BETWEEN @StartDate AND @EndDate
 ) as 'Cases Closed' ,
 (SELECT COUNT(*)  
 FROM tblTicket 
 WHERE DateIssued BETWEEN @StartDate AND @EndDate
 ) as 'Tickets Issued' ,
 (SELECT COUNT(*) 
 FROM tblWarning 
 WHERE DateIssued BETWEEN @StartDate AND @EndDate
 )  as 'Warnings Issued'
from dual

from dual would be necessary in oracle, mysql supports it but is not necessary and I'm not sure about sqlserver since I don't have one in front of me.

like image 99
Nathan Feger Avatar answered Jul 03 '26 07:07

Nathan Feger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!