受值限制 Postgresql 查询
Limited By Value Postgresql query
我有几行,其中一列中的值重复,我需要获取几行,其中每个值都受常量限制。
例如,我有这行 (1, 'a') (2, 'b') (3, 'a') (4,'c') (5 , 'b') (6, 'a') 并且我将 select 中的每个值限制为 2。然后我不应该得到 ID 为 6 的行,因为这是一个额外的行,因为我限制了它们2.
我该怎么做?
感谢您的帮助
如果您只有两列,比如 id
和 val
,并且您只希望每个值一行,那么聚合就足够了:
select min(id) as id, val
from mytable
group by val
如果列数较多,可以使用distinct on
:
select distinct on (val) t.*
from mytable
order by val, id
最后,如果您希望每个 val
允许可变行数,您可以使用 window 函数。假设您希望每个值最多 3 行:
select *
from (
select t.*, row_number() over(partition by val order by id) rn
from mytable t
) t
where rn <= 3
我有几行,其中一列中的值重复,我需要获取几行,其中每个值都受常量限制。
例如,我有这行 (1, 'a') (2, 'b') (3, 'a') (4,'c') (5 , 'b') (6, 'a') 并且我将 select 中的每个值限制为 2。然后我不应该得到 ID 为 6 的行,因为这是一个额外的行,因为我限制了它们2.
我该怎么做? 感谢您的帮助
如果您只有两列,比如 id
和 val
,并且您只希望每个值一行,那么聚合就足够了:
select min(id) as id, val
from mytable
group by val
如果列数较多,可以使用distinct on
:
select distinct on (val) t.*
from mytable
order by val, id
最后,如果您希望每个 val
允许可变行数,您可以使用 window 函数。假设您希望每个值最多 3 行:
select *
from (
select t.*, row_number() over(partition by val order by id) rn
from mytable t
) t
where rn <= 3