I’m doing some statistics based on a database of states. I would like to output the rank of a state and it’s percentage as compared to the other states (i.e. state X’s value is higher then 55% of the other states’ value).
I’m trying something like this:
SELECT
count(*) AS TotalStates,
(SELECT COUNT(*) FROM states) AS NumberStates,
(TotalStates/NumStates) AS percentage
FROM states
WHERE CRITERIA > 7.5
I’m getting an SQL error, TotalStates (my derived value) is not found. How can I get all three of these values returned with one query?
You can put the main calculations in a subselect, then reference the aliased columns in the outer query, both to pull the already calculated values and to obtain another one from them: