0

I want to basically take a number (total_score) and divide it by the number of (release_date)s that are <= today. I definitely want to do the math within the SELECT statement. I tried this but it doesn't seem to work:

SELECT 
total_score / COUNT(release_date <= CURDATE()) as final_score
from movies
WHERE id = 12

So say the total score is 400 and the number of release_dates that are <= today is 2. final_score should come out as 200.

Can I calculate within the SELECT statement like this? COUNT(release_date <= CURDATE())

1
  • Erm...I see what you are doing. You will need a subquery. Commented Mar 4, 2013 at 14:02

4 Answers 4

1

Maybe try this one:

SELECT 
total_score / (SELECT COUNT(release_date) FROM movies where release_date <= CURDATE()) as final_score
from movies
WHERE id = 12
Sign up to request clarification or add additional context in comments.

1 Comment

no problem, if it's an useful answer then maybe you can accept it as right answer to help other users.
0

One reason that doesn't work is you are only selecting one row (where id=12). You need to select from the table twice. Once to get the total_score for id 12, and another time to count the number of rows before CURDATE. Try something like:

select A.total_score / count(B.release_date) from movies as A, movies as B
   where A.id=12 and B.release_date <= CURDATE();

Comments

0

Maybe try something like this:-

SELECT (total_score / score_count) as final_score
FROM movies
CROSS JOIN (SELECT COUNT(*) as score_count
FROM movies
WHERE release_date <= CURDATE()) AS Sub1
WHERE id = 12

Comments

0

As per my assumption , Id is primary key(i.e Movie's ID). Then the query return always single row. Now to final_score is depends on release date. That release date must be previous to current date, so following query is enough to achieve you goal,

SELECT total_score / DATEDIFF(CURDATE(), release_date) AS final_score FROM movies WHERE id = 12

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.