开发者

SQL dividing 2 values from 2 queries

开发者 https://www.devze.com 2023-02-12 09:06 出处:网络
I have 2 queries that are as follows: SELECT COUNT(cvu.[ID]), \'Exp\' AS [Exp] FROM [dbo].[tblClientVehicleUnit] cvu

I have 2 queries that are as follows:

  SELECT COUNT(cvu.[ID]), 'Exp' AS [Exp]
    FROM [dbo].[tblClientVehicleUnit] cvu
    WHERE ExpirationDate < GetDa开发者_Go百科te()
    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


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


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


Try this: select (Query1) / (Query1)

in you Case it would be:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消