简体   繁体   English

如何在子查询中使用一个SQL查询的结果

[英]How to use results of one sql query within a sub-query

I have to answer the following question 我必须回答以下问题

"For each year in the database, list the year and the total number of movies that were released in that year, showing these totals in decreasing order. That is, the year(s) with the largest number of movies appear first. If some years have the same number of movies, show these in increasing order of year." “对于数据库中的每一年,请列出该年和该年发行的电影总数,并以降序显示这些总数。也​​就是说,电影数最大的年份排在最前面。如果有些年电影的数量相同,请按年升序显示。”

Currently I am using the code below to get the movies to group together, but am unable to get them to sort: 目前,我正在使用下面的代码将电影分组在一起,但是无法将它们排序:

Select YearReleased, count(*)                
from Movies                             
group by YearReleased 

I wish to use something to order this and am trying to make a sub query that uses the results of the first query, along the lines of: 我希望使用某种方式对此进行排序,并尝试通过以下方式创建一个使用第一个查询结果的子查询:

(select * from results order by count(*))

but so far I have been unsuccessful. 但到目前为止,我一直没有成功。 How do I achieve this or is there a better way of getting the results in that order? 我如何实现这一目标,或者有更好的方法来按顺序获得结果?

"Unsuccessful" isn't very useful, as opposed to actual error text -- and you aren't telling us which vendor's database you're running against, so we can't test. 与实际的错误文本相反,“不成功”不是很有用-而且您没有告诉我们您要针对哪个供应商的数据库运行,因此我们无法进行测试。 That said, the following should work: 也就是说,以下应该起作用:

select
  YearReleased,
  count(*) as movie_count
  from movies
  group by YearReleased
  order by movie_count desc, YearReleased;

No subqueries needed! 无需子查询!

Validated against SQLite 3.5.9; 根据SQLite 3.5.9验证; if running against something less standards-compliant (which SQLite is , except in very explicitly documented ways), your mileage may vary. 如果是在不符合标准的情况下运行(SQLite ,除非非常明确地记录在案,否则),您的里程可能会有所不同。

从*中选择*(从YearReleased从Movies组中选择YearReleased,count(*)作为NumReleased)由NumReleased排序

select * from (select YearReleased, count(*) counter
from Movies
group by YearReleased 
) a order by counter

May need a syntax change depending on your sql flavour. 可能需要更改语法,具体取决于您的sql风格。

在第一个查询中:选择yearReleased,在第二个查询中将count(*) 作为'count1' :按count1排序

是的,使用聚合,您可以为count(*)放置一个别名,并且可以将其作为一列引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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