Sql 如何根据每个重复ID的列中值的比较来“选择”行?

Sql 如何根据每个重复ID的列中值的比较来“选择”行?,sql,postgresql,greatest-n-per-group,Sql,Postgresql,Greatest N Per Group,我有一个表,看起来像这样,还有很多列: cid pid type C12 1 E C34 1 F C01 1 G 2 F 2 G 在以下情况下,我想“选择”最大值“cid”,并隐藏表中具有较小值的行: 1. 'cid' is present 2. 'pid' is the same 如果没有

我有一个表,看起来像这样,还有很多列:

cid        pid      type
C12         1         E
C34         1         F
C01         1         G
            2         F
            2         G
在以下情况下,我想“选择”最大值“cid”,并隐藏表中具有较小值的行:

 1. 'cid' is present
 2. 'pid' is the same
如果没有“cid”,则我没有任何东西可以“选择”最大行“cid”总是以“c”开头,不确定这是否会导致我失败,因为我正在尝试选择字母数字的最大值

新表应如下所示:

cid        pid      type
C34         1         F
            2         F
            2         G
我尝试过:

select max(cid) as cid from table. 
但它不起作用

也尝试了分组方式,但我有50个专栏,但仍然不起作用:

select max(cid) as cid, pid,type
from table
group by cid, pid, type
当我尝试仅按“pid”分组时,我得到一个错误,即我需要最终对所有列进行分组

--编辑--

我愿意删除表中的联接,该联接将在最后一个表中创建“cid”,并在有帮助的情况下执行单独的联接。理想情况下,我希望能够从现有表中“选择”所需的行

我将查询分为:cid exists和cid not exists:

一定要得到某个组的最大值,你可以使用DISTINCT ON子句,它总是给出一个有序组的第一条记录。在您的案例中,该组是pid,由cid按降序排列,以从最高到最高。这个记录就是结果。 在计算这些记录之后,只需合并这些记录,而不需要任何cid值。 不存在以下情况:

select t.* from tablename t
where t.cid is null
or not exists (
  select 1 from tablename
  where pid = t.pid and cid > t.cid
) 
看。 结果:

具有窗口功能:

select cid, pid, kind
from (
         select cid, pid, kind, row_number() over (partition by pid order by cid desc nulls last ) as rn
         from demo
     ) as T
where cid is null or rn = 1;
DB小提琴:

| cid | pid | type |
| --- | --- | ---- |
| C34 | 1   | F    |
|     | 2   | F    |
|     | 2   | G    |
select cid, pid, kind
from (
         select cid, pid, kind, row_number() over (partition by pid order by cid desc nulls last ) as rn
         from demo
     ) as T
where cid is null or rn = 1;