sql查询用空字符串或空字符串替换重复项

8fsztsew  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(434)

我使用的是oracle sql,表中有重复的行,如下所示:

Month   Product

March   ENVOY & External Keyboard (22)
March   ENVOY & External Keyboard (22)
March   ENVOY & External Keyboard (22)
March   ENVOY & External Keyboard (22)
March   ENVOY & External Keyboard (22)
March   ENVOY & External Keyboard (22)
April   ENVOY & External Keyboard (22)
April   ENVOY & External Keyboard (22)
April   ENVOY & External Keyboard (22)
April   ENVOY & External Keyboard (22)
April   ENVOY & External Keyboard (22)

我需要把它变成这样:

Month   Product

March   ENVOY & External Keyboard (22)
        ENVOY & External Keyboard (22)
        ENVOY & External Keyboard (22)
        ENVOY & External Keyboard (22)
        ENVOY & External Keyboard (22)
        ENVOY & External Keyboard (22)
April   ENVOY & External Keyboard (22)
        ENVOY & External Keyboard (22)
        ENVOY & External Keyboard (22)
        ENVOY & External Keyboard (22)
        ENVOY & External Keyboard (22)

我想用 SELECT (case when row_number() over (partition by times.calendar_month_name order by (select NULL)) = 1 then times.calendar_month_name end) Month 但不起作用。。。有什么想法吗?

dl5txlt9

dl5txlt91#

你可以用 LAG() 窗口功能:

select 
  nullif(Month, lag(Month) over (order by null)) Month,
  Product
from tablename

请看演示。
结果:

> MONTH | PRODUCT                       
> :---- | :-----------------------------
> March | ENVOY & External Keyboard (22)
>       | ENVOY & External Keyboard (22)
>       | ENVOY & External Keyboard (22)
>       | ENVOY & External Keyboard (22)
>       | ENVOY & External Keyboard (22)
>       | ENVOY & External Keyboard (22)
> April | ENVOY & External Keyboard (22)
>       | ENVOY & External Keyboard (22)
>       | ENVOY & External Keyboard (22)
>       | ENVOY & External Keyboard (22)
>       | ENVOY & External Keyboard (22)
yduiuuwa

yduiuuwa2#

小菜一碟sql*plus:

SQL> break on month
SQL>
SQL> select month, product from test order by month desc;

MONTH      PRODUCT
---------- ------------------------------
March      ENVOY & External Keyboard (22)
           ENVOY & External Keyboard (22)
           ENVOY & External Keyboard (22)
           ENVOY & External Keyboard (22)
           ENVOY & External Keyboard (22)
           ENVOY & External Keyboard (22)
April      ENVOY & External Keyboard (22)
           ENVOY & External Keyboard (22)
           ENVOY & External Keyboard (22)
           ENVOY & External Keyboard (22)
           ENVOY & External Keyboard (22)

11 rows selected.

SQL>
dohp0rv5

dohp0rv53#

这种类型的操作最好在应用程序级别完成。你可以用 row_number() ,但您需要小心:

select (case when seqnum = 1 then month end) as month, product
from (select t.*,
             row_number() over (partition by month order by month) as seqnum
      from t
     ) t
order by month, seqnum;

请注意,sql查询以不确定的顺序返回结果。所以你需要一个外罩 order by 以保证排序(即“第一”行具有值)。因为您要处理的是完全重复的,所以没有唯一的排序键,所以即使对 row_number() 可能产生不同的结果——因此使用子查询。

相关问题