I can’t write a condition that will allow me to count the total number of lines, divide them by the number of lines that contain the word Tetris and display the result of the division
Trying
Select count(*)
From table_name
Where main/(select main from table_name where main="Tetris")
The data that you get from the database is only what you put in the SELECT clause. The WHERE clause is exclusively here to filter according to a predicate.
Your query would work by just moving the troublesome part inside the SELECT clause. Note that to have a ratio, you need to convert COUNT(*) to a floating-point number with a cast operation.
Lastly, string values in sql are single-quoted. Double-quotes are for identifiers.
SELECT COUNT(*)::DECIMAL / (SELECT COUNT(*) FROM table_name WHERE main='Tetris')
FROM table_name
A slightly better version of the above makes use of FILTER for aggregation functions:
SELECT COUNT(*)::DECIMAL / COUNT(*) FILTER (WHERE main='Tetris')
FROM table_name
Or here is a version with CASE, that makes use of the fact that NULL values do not participate to the counts.
SELECT COUNT(*)::DECIMAL / COUNT(CASE WHEN main='Tetris' THEN 1 ELSE NULL END)
FROM table_name
What you are trying to compute is the reciprocal of the occurrence rate of ‘tetris’. Other than the various possible solutions offered by Atmo, here is an alternative using the aggregate function AVG.
SELECT 1.0 / AVG(CASE WHEN main = 'tetris' THEN 1.0 ELSE 0.0 END)
FROM table_name;
3
Answers
The data that you get from the database is only what you put in the
SELECT
clause. TheWHERE
clause is exclusively here to filter according to a predicate.Your query would work by just moving the troublesome part inside the
SELECT
clause. Note that to have a ratio, you need to convertCOUNT(*)
to a floating-point number with a cast operation.Lastly, string values in
sql
are single-quoted. Double-quotes are for identifiers.A slightly better version of the above makes use of
FILTER
for aggregation functions:Or here is a version with
CASE
, that makes use of the fact thatNULL
values do not participate to the counts.You could sum one for every row divided by the sum of every Tetris row:
What you are trying to compute is the reciprocal of the occurrence rate of ‘tetris’. Other than the various possible solutions offered by Atmo, here is an alternative using the aggregate function AVG.