简体   繁体   English

使用SQL查询进入ORDER BY子句

[英]Using SQL query into ORDER BY clause

I have tables USERS and REPORTS . 我有表USERSREPORTS In the REPORTS table, I have a column user_id so I can count how many reports the users gave. REPORTS表中,我有一列user_id因此我可以计算用户提供的报告数。 What I want to do is to get first 10 users that gave the most reports. 我想要做的是让前10名用户提供最多的报告。

I thought about the next query: 我想到了下一个查询:

SELECT 
    * 
FROM 
    (SELECT users.id 
     FROM users 
     ORDER BY (SELECT count(*) 
               FROM reports 
               WHERE user_id = "users.id") DESC) 
WHERE 
    ROWNUM <= 10;

But, I don't know how to use the ID that was returned from the main query into subquery. 但是,我不知道如何使用从主查询返回到子查询的ID。

I use Oracle 11g. 我使用Oracle 11g。

Later edit I managed to sort the results with GROUP BY: 后来编辑,我设法用GROUP BY对结果进行排序:

SELECT * FROM(SELECT user_id, count(*) as count1 FROM reports GROUP BY     
user_id ORDER BY count1 DESC) WHERE ROWNUM <= 10

This can be done by combining group by with a window function: 这可以通过组合group by和窗口函数来完成:

select u.*, r.num_reports
from users u
  join (
    select user_id, 
           count(*) as num_reports, 
           dense_rank() over (order by count(*) desc) as rnk
    from reports
    group by user_id
  ) r on u.id = r.user_id and r.rnk <= 10
order by r.num_reports desc;

The derived table (the "inner" select) counts the number of reports per user and also ranks those rows based on the number of reports. 派生表(“内部”选择)对每个用户的报告数进行计数,并根据报告数对这些行进行排名。 The highest number will get rank = 1, the second highest 2 and so on. 最高的数字将获得等级= 1,第二高的则为2,依此类推。 Those users with a rank higher then 10 will be filtered out in the join condition. 那些排名高于10的用户将在加入条件下被过滤掉。 Note that this can potentially return more then 10 users if there are users in the "top-10" that have the same number of reports. 请注意,如果“前10名”中的用户具有相同数量的报告,则这有可能返回10个以上的用户。

Sorry this should work 抱歉,这应该可以

SELECT * 
FROM   sometable
ORDER BY name
FETCH FIRST 10 ROWS ONLY
SELECT * 
FROM   (
  SELECT u.id 
  FROM   users u
         INNER JOIN
         (
           SELECT user_id,
                  count(*) AS num_reports
           FROM   reports
           GROUP BY user_id
         ) r
         ON ( u.id = r.user_id )
  ORDER BY r.num_reports DESC
)
WHERE ROWNUM <= 10;

or, more simply: 或者,更简单地说:

SELECT * 
FROM   (
  SELECT user_id
  FROM   reports
  GROUP BY user_id
  ORDER BY COUNT(*) DESC
)
WHERE ROWNUM <= 10;

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

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