[英]How to “Pick” row based on comparison of value in columns for every ID that is duplicated?
我有一個看起來像這樣的表(多列):
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.
但它不起作用。
也嘗試了group by
,但是我有50列,但仍然無法正常工作:
select max(cid) as cid, pid,type
from table
group by cid, pid, type
當我嘗試僅按“ pid”分組時,出現錯誤,我最終需要對所有列進行分組。
- -編輯 - -
我願意刪除在最終表中創建“ 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
)
參見演示 。
結果:
| cid | pid | type |
| --- | --- | ---- |
| C34 | 1 | F |
| | 2 | F |
| | 2 | G |
SELECT
*
FROM (
SELECT DISTINCT ON (pid)
*
FROM
mytable
WHERE cid IS NOT NULL
ORDER BY pid, cid DESC
) s
UNION ALL
SELECT
*
FROM
mytable
WHERE cid IS NULL
我將查詢分為: cid
存在和cid
不存在:
DISTINCT ON
子句,該子句始終給出有序組的第一條記錄。 在您的情況下,組是pid
並且按cid
排序(以DESC
結尾),以使最高的組排在最前面。 該記錄是結果。 UNION
記錄即可,沒有任何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小提琴: https : //www.db-fiddle.com/f/kPjgji1w2hm51JaBFGQzCL/0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.