简体   繁体   中英

MySQL: Calculate number using COUNT within the SELECT statement?

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())

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

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

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();

As per my assumption , Id is primary key(ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM