首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于两个字段的PostgreSQL数据分组

基于两个字段的PostgreSQL数据分组
EN

Stack Overflow用户
提问于 2021-06-02 08:25:23
回答 2查看 27关注 0票数 0

我对postgresql中的数据分组有问题。假设我有一个名为my_table的表

代码语言:javascript
复制
some_id  | description     | other_id
---------|-----------------|-----------
1        | description-1   |  a
1        | description-2   |  b
2        | description-3   |  a
2        | description-4   |  a
3        | description-5   |  a
3        | description-6   |  b
3        | description-7   |  b
4        | description-8   |  a
4        | description-9   |  a
4        | description-10  |  a
...

我想根据some_id对我的数据库进行分组,然后区分哪一个具有相同的和不同的other_id

我希望有两种类型的查询:一个有相同的other_id,一个有不同的other_id

预期结果

代码语言:javascript
复制
some_id  | description     | other_id
---------|-----------------|-----------
2        | description-3   |  a
2        | description-4   |  a
4        | description-8   |  a
4        | description-9   |  a
4        | description-10  |  a

代码语言:javascript
复制
some_id  | description     | other_id
---------|-----------------|-----------
1        | description-1   |  a
1        | description-2   |  b
3        | description-5   |  a
3        | description-6   |  b
3        | description-7   |  b

我愿意接受建议,无论是使用续集还是原始查询。

谢谢

EN

回答 2

Stack Overflow用户

发布于 2021-06-02 08:34:35

一种方法是使用MINMAX作为分析函数:

代码语言:javascript
复制
WITH cte AS (
    SELECT *, MIN(other_id) OVER (PARTITION BY some_id) min_other_id,
              MAX(other_id) OVER (PARTITION BY some_id) max_other_id
    FROM yourTable
)

-- all some_id the same
SELECT some_id, description, other_id
FROM cte
WHERE min_other_id = max_other_id;

-- not all some_id the same
SELECT some_id, description, other_id
FROM cte
WHERE min_other_id <> max_other_id;

Demo

票数 0
EN

Stack Overflow用户

发布于 2021-06-02 11:00:19

您也可以使用existsnot exists来完成这一任务。

代码语言:javascript
复制
-- all same
select t.*
from my_table t
where not exists (select 1
                  from my_table t2
                  where t2.some_id = t.some_id and t2.other_id <> t.other_id
                 );

-- any different

select t.*
from my_table t
where exists (select 1
              from my_table t2
              where t2.some_id = t.some_id and t2.other_id <> t.other_id
             );

请注意,这会忽略NULL值。如果希望将它们视为“不同”值,则使用is distinct from而不是<>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67801536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档