简体   繁体   中英

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

You could use conditional aggregation:

SELECT 100.0*COUNT(CASE WHEN EProj = 'abc' AND EID = '101' THEN EUpdate END) /
             COUNT(CASE WHEN EID = '101' THEN Eproj END) AS percentage
FROM EmpUpdates;

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 null s:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM