SQL从2个查询中划分2个值

时间:2011-02-22 15:08:31

标签: sql sql-server-2005

我有2个查询,如下所示:

  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'

我如何划分这两者之间的数量?它总是只返回2个值,一个将被称为Exp,一个将被称为NonExp。

由于

4 个答案:

答案 0 :(得分:16)

基本上将这两个查询视为子查询,如下所示。

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

如果你想更进一步,你可以将cvu.id作为选择的一部分并修改连接,这样你就可以在所有cvu.id的

中完成它。
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

答案 1 :(得分:2)

以下是我刚才所做的事情,它展示了如何将结果从两个单独的查询中划分出来 - 您必须将它们转换为可分割的数据类型,以获得除零以外的结果:

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

答案 2 :(得分:0)

试试这个:     select(Query1)/(Query1)

在你的情况下它将是:

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

答案 3 :(得分:0)

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