简体   繁体   English

如果所选列 postgresql sql 的列中的数据相同,则 Null 行值

[英]Null row value if data same in column for selected column postgresql sql

I have a table like this:我有一张这样的桌子:

  cms_code  | product 
------------+---------
 55381XA384 | MS
 55381XA384 | MS
 55381XA384 | HSD
 55381XA384 | HSD
 55381XA382 | HSD
 55381XA382 | XP
 55381XA382 | MS
 55381XA382 | HSD
 55381XA382 | HSD

Now, I need a result like this:现在,我需要这样的结果:

  cms_code  | product 
------------+---------
 55381XA384 | MS
 NULL       | MS
 NULL       | HSD
 NULL       | HSD
 55381XA382 | HSD
 NULL       | XP
 NULL       | MS
 NULL       | HSD
 NULL       | HSD

you can use window functions to number the rows & set subsequent values to null , keeping the cms_code only for row number 1.您可以使用 window 函数对行进行编号并将后续值设置为null ,仅将cms_code保留为行号 1。

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

Your results depend on the ordering of the rows.您的结果取决于行的顺序。 SQL tables represent unordered sets, so you cannot do what you want with the data you have. SQL 表表示无序集,因此您无法对拥有的数据做任何事情。

Assuming you have a column that specifies the ordering, you could do:假设您有一个指定排序的列,您可以执行以下操作:

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>;

Without an ordering column, you can also do:如果没有排序列,您还可以执行以下操作:

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;

In both cases, you need the order by in the outer query to guarantee that the result set is ordered so the "first" row has the cms_code .在这两种情况下,您都需要外部查询中的order by以保证结果集是有序的,因此“第一”行具有cms_code

I'm assuming you want null for all the values of cms_code which is same after the first value.我假设您需要 null 的 cms_code 的所有值,这在第一个值之后是相同的。 Correct me if I'm wrong Below query can be used for the same:如果我错了,请纠正我下面的查询可以用于相同的目的:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM