Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing arithmetic operations on derived SQL values

Tags:

sql

mysql

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?

like image 458
MarathonStudios Avatar asked Dec 05 '11 05:12

MarathonStudios


People also ask

Can SQL perform arithmetic operations?

We can use various Arithmetic Operators on the data stored in the tables.

Can we perform arithmetic operations on null values in SQL?

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.

Can we use arithmetic operators in WHERE clause SQL?

Arithmetic operators can also be used in the WHERE clause to restrict the data returned.

What operations can be performed in SQL?

There are six types of SQL operators that we are going to cover: Arithmetic, Bitwise, Comparison, Compound, Logical and String.


2 Answers

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
like image 119
Andriy M Avatar answered Oct 08 '22 09:10

Andriy M


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?

like image 44
Joseph Alcorn Avatar answered Oct 08 '22 10:10

Joseph Alcorn