如何根据列数据获得前150个结果

时间:2018-01-10 17:52:49

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

我有一个TEMP_TABLE,其中包含以下数据

SOURCE - Number
DESTINATION- Number
COUNT- Number (Total count of transactions)
SUM- Number (Total sum of transactions)

示例数据:

SOURCE    DESTINATION COUNT SUM
123123123 99009900    65    1000000
123123123 88880303    12    90000
191113111 98980101    277   5000000
191113111 77778585    5     20000
191113111 56789547    740   75000000

我试图根据150 results的值,按source number with the destination number获得热门COUNT。如果123123123在包含多个目的地的表格中有200行,我会尝试获取123123123的前150个结果,并排除其他50行。

1 个答案:

答案 0 :(得分:2)

您可以使用row_number窗口功能为每一行(每个源编号)分配一个编号,然后只为每一行分配前150个:
(注意:sumcount是Oracle SQL中的保留字。为避免丑陋的转义,下面的示例分别将它们重命名为sum_colcount_col

SELECT source, destination, count_col, sum_col
FROM   (SELECT source, destination, count_col, sum_col,
               ROW_NUMBER() OVER (PARTITION BY source
                                  ORDER BY count_col DESC) AS rn
        FROM   temp_table) t
WHERE  rn <= 150