SQL dividing 2 values from 2 queries

谁都会走 提交于 2020-01-13 11:05:24

问题


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


回答1:


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



回答2:


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



回答3:


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')



回答4:


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' )


来源:https://stackoverflow.com/questions/5079879/sql-dividing-2-values-from-2-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!