I have this query where I am working out the percentage of peoples occupation. I have a sub query that works out the total count of people codes and that result is what I used to divide by. I could hardcode this but the count could change.
It just looks a bit messy and I am wondering if there is a nicer way to do the sub query.
SELECT
CONVERT(VARCHAR(20),COUNT(CO.code)*100 /
(
SELECT
COUNT(CO.Code)
FROM
TABLE1 K
INNER JOIN TABLE2 CO ON(CO.id= K.id AND CO.status= 'Something' AND K.statuscode = 0 AND CO.statuscode =0))
)+'%',
Here is the final query. I needed the sub query because of the group by which if I did the count in the SELECT
, it would just return the number of people who had a specific occupation.
SELECT
CONVERT(VARCHAR(20),COUNT(CO.code)*100 /
(
SELECT
COUNT(CO.Code)
FROM
TABLE1 K
INNER JOIN TABLE2 CO ON(CO.id= K.id AND CO.status= 'Something' AND K.statuscode = 0 AND CO.statuscode =0))
)+'%',
K.occupation
FROM
TABLE 1 K
LEFT OUTER TABLE 2 CO ON(CO.id = K.id AND CO.status = 'Something' AND K.statuscode = 0 AND CO.statuscode = 0)
GROUP BY
K.occupation
ORDER BY
COUNT(CO.Code) DESC
Is there a nicer/more efficient way to do this?