Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL dividing 2 values from 2 queries

I have 2 queries that are as follows:

  SELECT COUNT(cvu.[ID]), 'Exp' AS [Exp]
    FROM [dbo].[tblClientVehicleUnit] cvu
    WHERE ExpirationDate < GetDate()
    AND cvu.Id = '4C1'

And the second one:

SELECT COUNT(cvu.[ID]), 'NonExp' AS [Exp]
    FROM [dbo].[tblClientVehicleUnit] cvu
    WHERE ExpirationDate > GetDate()
    AND cvu.Id = '4C1'

How would I divide the counts between these two? It will always only return 2 values and one will be called Exp and one will be called NonExp.

Thanks

like image 923
user380432 Avatar asked Feb 22 '11 15:02

user380432


2 Answers

Basically treat those two queries as sub queries as below.

select x.number / y.number 
from
(
  SELECT COUNT(cvu.[ID]) as number, 'Exp' AS [Exp]     
  FROM [dbo].[tblClientVehicleUnit] cvu     
  WHERE ExpirationDate < GetDate()     
  AND cvu.Id = '4C1' 
) x
join 
(
  SELECT COUNT(cvu.[ID]) as number, 'NonExp' AS [Exp]     
  FROM [dbo].[tblClientVehicleUnit] cvu     
  WHERE ExpirationDate > GetDate()     
  AND cvu.Id = '4C1'
) y on 1=1

If you wanted to take it further you could then have the cvu.id as part of the select and modify the join so you could do it across all cvu.id's

select x.id, x.number / y.number 
from
(
SELECT cvu.id, COUNT(cvu.[ID]) as number, 'Exp' AS [Exp]     
FROM [dbo].[tblClientVehicleUnit] cvu     
WHERE ExpirationDate < GetDate()     
group by cvu.Id 
) x
join 
(
SELECT cvu.id, COUNT(cvu.[ID]) as number, 'NonExp' AS [Exp]     
FROM [dbo].[tblClientVehicleUnit] cvu     
WHERE ExpirationDate > GetDate()     
group by cvu.Id 
)y on x.id = y.id
like image 71
AgentDBA Avatar answered Oct 03 '22 04:10

AgentDBA


Here's something I just did that shows how to divide the results from two separate queries--you have to CAST them to a divisible datatype in order to get a result other than Zero:

WITH 
T1 AS (SELECT DISTINCT COUNT(StudID) as NumA FROM TBL WHERE MetTarget = 'Y'), 
T2 AS (SELECT COUNT( DISTINCT FallScore + SprgScore ) as NumB FROM TBL) 
SELECT CAST(T1.NumA AS FLOAT) / CAST(T2.NumB AS FLOAT) * 100 as PctMetTgt
FROM T1, T2
like image 20
Da Rock Avatar answered Oct 03 '22 05:10

Da Rock