使用SQL查询到ORDER BY子句

时间:2017-05-04 20:18:29

标签: sql oracle greatest-n-per-group

我有表USERSREPORTS。在REPORTS表格中,我有一列user_id,因此我可以计算用户提供的报告数量。我想要做的是获得报告最多的前10位用户。

我想到了下一个问题:

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

但是,我不知道如何将主查询返回的ID用于子查询。

我使用的是Oracle 11g。

稍后修改 我设法用GROUP BY对结果进行排序:

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

2 个答案:

答案 0 :(得分:0)

抱歉这应该有用

convert xc:"rgba(255,0,0,1)" xc:"rgba(0,0,0,1)" xc:"rgba(0,0,0,0)" -depth 8 -evaluate-sequence mean txt:

答案 1 :(得分:0)

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;

或更简单地说:

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