Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

SQL che divide 2 valori da 2 query

Fondamentalmente tratta queste due query come sottoquery come di seguito.

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

Se vuoi andare oltre, puoi avere cvu.id come parte della selezione e modificare il join in modo da poterlo fare su tutti i 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