Redshift中的ROW_NUMBER()从每个组中选择最大行?

时间:2013-11-14 09:53:49

标签: amazon-redshift

我需要根据COUNT(1)字段从每个组中选择一行。

在其他数据库中,我使用ROW_NUMBER()函数,该函数在redshift中为unsupported yet

1 个答案:

答案 0 :(得分:6)

答案是使用SUM(1) OVER(PARTITION BY group_field ORDER BY order field ROWS UNBOUNDED PRECEDING)这样的结构:

SELECT id,
       name,
       cnt
FROM
  (SELECT id,
          name,
          count(*) cnt,
          sum(1) over (partition BY id ORDER BY cnt DESC ROWS UNBOUNDED PRECEDING) AS row_number
   FROM table
   GROUP BY id,
            name)
WHERE row_number = 1
ORDER BY name