postgresql 如果选定列的列中的数据相同,则为空行值

5t7ly7z5  于 2023-05-28  发布在  PostgreSQL
关注(0)|答案(3)|浏览(149)

我有一张这样的table:
| CMS码|产物|
| - -----|- -----|
| 55381XA384| MS|
| 55381XA384| MS|
| 55381XA384| HSD|
| 55381XA384| HSD|
| 55381XA382| HSD|
| 55381XA382| XP|
| 55381XA382| MS|
| 55381XA382| HSD|
| 55381XA382| HSD|
现在,我需要一个这样的结果:
| CMS码|产物|
| - -----|- -----|
| 55381XA384| MS|
| 空值|MS|
| 空值|HSD|
| 空值|HSD|
| 55381XA382| HSD|
| 空值|XP|
| 空值|MS|
| 空值|HSD|
| 空值|HSD|

5us2dqdw

5us2dqdw1#

结果取决于行的顺序。SQL表表示 * 无序 * 集,因此您无法对现有数据做任何您想要做的事情。
假设你有一个指定排序的列,你可以做:

select (case when row_number() over (partition by cms_code order by <ordering col< = 1
             then cms_code
        end) as cms_code, product_code
from t
order by cms_code, <ordering col>;

如果没有排序列,您还可以执行以下操作:

with cte as (
      select t.*, row_number() over (partition by cms_code order by cms_code) as seqnum
      from t
     )
select (case when seqnum = 1 then cms_code end) as cms_code,
       product_code
from t
order by cms_code, seqnum;

在这两种情况下,您都需要在外部查询中使用order by来保证结果集是有序的,因此“第一”行具有cms_code

hs1ihplo

hs1ihplo2#

你可以使用窗口函数来对行进行编号,并将后续的值设置为null,只保留第1行的cms_code

select 
  case 
    when row_number() over (partition by cms_code) = 1 then cms_code 
    else null 
  end cms_code
, product_code
from my_table
order by cms_code
q43xntqr

q43xntqr3#

我假设你希望cms_code的所有值都为null,它在第一个值之后是相同的。如果我错了,请纠正我下面的查询可以用于相同的:

SELECT 
  CASE
    WHEN ROW_NUMBER() OVER(PARTITION BY cms_code order by product) = 1 
    THEN NULL 
    ELSE cms_code 
  END AS cms_code,product 
FROM table;

相关问题