PostgreSQL distinct and group on different fields
PostgreSQL distinct and group on different fields
通过以下查询,我可以获得在成员资格 table 中添加的项目成员列表,与项目所有者联合(他们可能在成员资格中没有条目 table )
select sub.user, sub.project, sub.role, sub.order, sub.name from
(SELECT
memberships."user",
memberships.project,
memberships.role,
roles."order",
roles.name
FROM memberships
JOIN roles ON roles.id = memberships.role
UNION
SELECT projects.owner AS "user",
projects.id AS project,
1 AS role,
0 AS "order",
'admin'::text AS name
FROM projects
) as sub
上述查询产生以下结果集。
8 2 1 0 "admin"
8 1 3 2 "contributor" (added through memberships table)
6 1 1 0 "admin"
8 4 1 0 "admin"
8 1 1 0 "admin" (duplicate because user #8 is the owner of project #1)
现在我想通过获取最少 order
的行的内容来删除重复的条目。使用 distinct on (sub.order)
不包括所有行
select distinct on (sub.order) * from
-- the same subquery
order by sub.order
以上结果
8 2 1 0 "admin"
8 1 3 2 "contributor"
使用 group by sub.user, sub.project
并聚合 min(sub.order)
有效,但其他两个字段如 role
和 name
被排除在外
select sub.user, sub.project, min(sub.order) from
-- the same subquery
group by sub.user, sub.project
我想要 role
、name
和 order
与 user, project
对[=26= 分组时具有最小 order
的行]
I want the role, name and order of the row that has the minimum order when grouped with user, project pair
distinct on
必须枚举“分组”列 - 然后 order by
子句必须包含相同的列,后跟用于打破关系的列。
你可能想要:
select distinct on (t.user, t.project) *
from (
-- the same subquery --
) t
order by t.user, t.project, t.order
通过以下查询,我可以获得在成员资格 table 中添加的项目成员列表,与项目所有者联合(他们可能在成员资格中没有条目 table )
select sub.user, sub.project, sub.role, sub.order, sub.name from
(SELECT
memberships."user",
memberships.project,
memberships.role,
roles."order",
roles.name
FROM memberships
JOIN roles ON roles.id = memberships.role
UNION
SELECT projects.owner AS "user",
projects.id AS project,
1 AS role,
0 AS "order",
'admin'::text AS name
FROM projects
) as sub
上述查询产生以下结果集。
8 2 1 0 "admin"
8 1 3 2 "contributor" (added through memberships table)
6 1 1 0 "admin"
8 4 1 0 "admin"
8 1 1 0 "admin" (duplicate because user #8 is the owner of project #1)
现在我想通过获取最少 order
的行的内容来删除重复的条目。使用 distinct on (sub.order)
不包括所有行
select distinct on (sub.order) * from
-- the same subquery
order by sub.order
以上结果
8 2 1 0 "admin"
8 1 3 2 "contributor"
使用 group by sub.user, sub.project
并聚合 min(sub.order)
有效,但其他两个字段如 role
和 name
被排除在外
select sub.user, sub.project, min(sub.order) from
-- the same subquery
group by sub.user, sub.project
我想要 role
、name
和 order
与 user, project
对[=26= 分组时具有最小 order
的行]
I want the role, name and order of the row that has the minimum order when grouped with user, project pair
distinct on
必须枚举“分组”列 - 然后 order by
子句必须包含相同的列,后跟用于打破关系的列。
你可能想要:
select distinct on (t.user, t.project) *
from (
-- the same subquery --
) t
order by t.user, t.project, t.order