简体   繁体   中英

Getting number of rows of a query as output when COUNT(*) can't be used

I have this query that returns 13 rows.

SELECT DISTINCT title,year FROM MovieAwards WHERE EXISTS (SELECT DISTINCT * FROM Movies WHERE MovieAwards.title = Movies.title AND Movies.year = MovieAwards.year AND Movies.year >= 2000 AND Movies.year <= 2010 AND MovieAwards.result='won');

Now i need to use the number of rows of this query as a float for other queries. I am aware that i can use THIS AND AS to store the number of rows in some temporary variable. But i can't find a single way to modify the first query to output 13.

If i do SELECT COUNT(*) FROM MovieAwards WHERE EXISTS IN (the code above)

i get a very different number as title,year is not the key of MovieAwards.

I also tried to replace title,year with count(title,year) but i'm guessing that isn't allowed.

I can't think of anything else to try. Any help would be apretiated.

Edit: Thanks @nbk for your code. Individually it works perfectly. However when I try to use it I get either a syntax error or a casting error. This last attempt below in particular gives a generic syntax error:

WITH
"won" AS
(SELECT COUNT(*)::FLOAT
  FROM MovieAwards 
  WHERE EXISTS (SELECT DISTINCT * FROM Movies WHERE MovieAwards.title = Movies.title AND Movies.year = MovieAwards.year AND Movies.year >= 2000 AND Movies.year <= 2010 AND MovieAwards.result='won')
GROUP BY title,year),

"total" AS
(SELECT COUNT(*)::FLOAT
FROM Movies
WHERE Movies.year >=2000 AND Movies.year <=2010)

SELECT success-rate AS ( CASE WHEN (total = 0) THEN '-1' (ELSE won/total) );


You can select the count of some literal to get a count for your selection. Please refer below.

SELECT COUNT(1) FROM (SELECT DISTINCT title,year FROM MovieAwards WHERE EXISTS (SELECT DISTINCT * FROM Movies WHERE MovieAwards.title = Movies.title AND Movies.year = MovieAwards.year AND Movies.year >= 2000 AND Movies.year <= 2010 AND MovieAwards.result='won'));

You can GROUP BY title and year and count the result

SELECT COUNT(*)::FLOAT
  FROM MovieAwards 
  WHERE EXISTS (SELECT DISTINCT * FROM Movies WHERE MovieAwards.title = Movies.title AND Movies.year = MovieAwards.year AND Movies.year >= 2000 AND Movies.year <= 2010 AND MovieAwards.result='won')
GROUP BY "title","year";
count
SELECT 0

fiddle

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