对于查询中的每一行,从其他查询中选择前20位

时间:2009-11-09 13:58:55

标签: sql oracle select

我正在尝试做某事,我不知道该怎么做。

我有一些这样的数据:

WITH a AS (SELECT   theid, thename, thetimestamp FROM mytable)
SELECT   thename, TRUNC (thetimestamp, 'HH24'), COUNT (theid) FROM   a
group by thename,trunc(thetimestamp,'HH24') ORDER BY COUNT (theid) desc)

返回按小时和名称分组的计数。

我希望它只是

for each hour, top X counts

这可能吗?


我结束了:

SELECT thename, hour, cnt
FROM
( SELECT thename, hour, cnt,
         rank() over (partition by hours order by cnt desc) rnk
  FROM
  ( SELECT   thename, TRUNC (thetimestamp, 'HH24') hour, COUNT (theid) cnt 
    FROM mytable
    group by thename,trunc(thetimestamp,'HH24')
  )
)
WHERE rnk <= :X

2 个答案:

答案 0 :(得分:3)

尝试:

SELECT thename, hour, cnt
FROM
( SELECT thename, hour, cnt,
         rank() over (partition by thename order by cnt desc) rnk
  FROM
  ( SELECT   thename, TRUNC (thetimestamp, 'HH24') hour, COUNT (theid) cnt 
    FROM mytable
    group by thename,trunc(thetimestamp,'HH24')
  )
)
WHERE rnk <= :X

(我没有看到WITH子句的目的,所以我把它从我的中删除了。)

答案 1 :(得分:2)

你可以用row_number()做到这一点,但它需要另一个子查询或另一个CTE。这是双CTE,因为Tony Adrews已经发布了子查询方法:

WITH a AS (
    SELECT thename, TRUNC(thetimestamp, 'HH24') as hour, COUNT(*) cnt
    FROM  mytable
    GROUP BY thename, TRUNC(thetimestamp, 'HH24')
), b AS (
    SELECT 
        ROW_NUMBER() OVER (PARTITION BY hour ORDER BY ctn DESC) rn,
        thename, hour, cnt
    FROM a
)
SELECT *
FROM b
WHERE rn < 20