SQL ORDER BY GROUP BY

时间:2013-03-12 18:54:02

标签: sql group-by oracle11g sql-order-by

我有两个按ID链接的表(ENTRIES和USERS),我想只选择前5位用户的所有条目,然后按个别用户条目的COUNT排序。

USERS    ENTRIES

tom      entry1
mary     entry2
jane     entry3
tom      entry4
tom      entry5

等...... 显示为

USERS    ENTRIES

tom      entry1
tom      entry4
tom      entry5
jane     entry3
mary     entry2

我的代码目前仅按名称排序,但未按COUNT个条目列出

SELECT  ENTRIES.entry, USERS.NAME   FROM ENTRIES, USERS 
WHERE ENTRIES.USER_ID = USERS.ID 
ORDER BY USERS.NAME 

1 个答案:

答案 0 :(得分:3)

由于您使用的是Oracle,因此您可以使用窗口函数来获取每个用户的总计数:

SELECT e.entry, 
  u.NAME,
  count(*) over(partition by u.name) Total
FROM ENTRIES e
INNER JOIN USERS u
  ON e.USER_ID = u.ID 
ORDER BY total desc, u.NAME

请参阅SQL Fiddle with Demo

如果您想只返回前5行,则可以使用:

select entry,
  name,
  total
from 
(
  SELECT e.entry, 
    u.NAME,
    count(*) over(partition by u.name) Total,
    rownum rn
  FROM ENTRIES e
  INNER JOIN USERS u
    ON e.USER_ID = u.ID
) 
where rn <= 5
ORDER BY total desc, NAME

请参阅SQL Fiddle with Demo