2

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

在其他数据库中,我会使用 ROW_NUMBER() 函数,该函数在 redshift 中尚不受支持

4

1 回答 1

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
于 2013-11-14T09:53:48.593 回答