You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL按some_id分组后区分other_id是否一致的查询方法

解决方案

原始SQL实现

核心思路是通过窗口函数给每个some_id分组计算去重后的other_id数量,再基于这个数量过滤对应分组的全量数据:

1. 查询分组内other_id完全相同的全量数据

SELECT some_id, description, other_id
FROM (
    SELECT 
        *,
        COUNT(DISTINCT other_id) OVER (PARTITION BY some_id) AS distinct_other_cnt
    FROM my_table
) t
WHERE distinct_other_cnt = 1;

2. 查询分组内存在不同other_id的全量数据

SELECT some_id, description, other_id
FROM (
    SELECT 
        *,
        COUNT(DISTINCT other_id) OVER (PARTITION BY some_id) AS distinct_other_cnt
    FROM my_table
) t
WHERE distinct_other_cnt > 1;

如果数据量较大,也可以用子查询先过滤符合条件的some_id再关联原表,性能更优:

-- 第一类查询示例(第二类仅需把HAVING条件改为COUNT(DISTINCT other_id) > 1即可)
SELECT m.*
FROM my_table m
INNER JOIN (
    SELECT some_id
    FROM my_table
    GROUP BY some_id
    HAVING COUNT(DISTINCT other_id) = 1
) filtered_some_id ON m.some_id = filtered_some_id.some_id;

Sequelize实现

以第一类查询为例,第二类仅需修改判断条件即可:

const result = await MyTable.findAll({
    attributes: ['some_id', 'description', 'other_id'],
    // 直接用窗口函数实现写法更简洁
    attributes: [
        'some_id', 'description', 'other_id',
        [sequelize.literal(`COUNT(DISTINCT other_id) OVER (PARTITION BY some_id)`), 'distinct_other_cnt']
    ],
    having: sequelize.literal(`distinct_other_cnt = 1`)
});

内容的提问来源于stack exchange,提问作者ryanadhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 17:06:06