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?
We can use various Arithmetic Operators on the data stored in the tables.
If you do any arithmetic operations with null the whole expression evaluates to Null. In order to handle null you should use Isnull() or coalesce function like this.
Arithmetic operators can also be used in the WHERE clause to restrict the data returned.
There are six types of SQL operators that we are going to cover: Arithmetic, Bitwise, Comparison, Compound, Logical and String.
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:
SELECT
TotalStates,
NumberStates,
TotalStates / NumberStates AS percentage
FROM (
SELECT
COUNT(*) AS TotalStates,
(SELECT COUNT(*) FROM states) AS NumberStates
FROM states
WHERE CRITERIA > 7.5
) s
The error you are getting comes from the fact that you are trying to use the derived value in the same select clause that you are creating it in. You will need to maybe do something along these lines:
SELECT count(*) as TotalStates,
(SELECT count(*) from states) as NumberStates,
(count(*)/(SELECT count(*) from states)) as percentage
FROM states
WHERE criteria = x
However, this is not very efficient or desirable for readability or maintainability. Is there a design reason that you cannot perform this in two queries, or better yet, get the two data items in separate queries and calculate the percentage in the consuming code?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With