Skip to content
Advertisement

How can I calculate a percentage from values obtained by 2 different queries in SSMS?

First query:

select COUNT(EUpdate) 
from EmpUpdates 
where EProj = 'abc' and EID = '101';

Second query:

select COUNT(EProj) 
from EmpUpdates 
where EID = '101';

percentage = (first query / second query) * 100

Advertisement

Answer

You can do conditional aggregation. Unless there are null values in eupdate and eproj, I would recommend avg()

select avg(case when eproj = 'abc' then 100.0 else 0 end) res
from empupdates 
where eid = 101

If you really need to deal with nulls:

select 100.0 * count(case when eproj = 'abc' then eupdate end) / count(eproj) res
from empupdates 
where eid = 101

I removed the single quotes around eid, because it looks like a number; if it’s really a string, then you can revert that change.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement