清除特定行的列中的字符串

时间:2017-09-22 11:52:05

标签: sql sql-server-2012

我有一张看起来像这样的表:

| col1 | ... | colx |
---------------------
|  1   | ... | dfd  |
|  1   | ... | ajd  |
|  1   | ... | aad  |
|  2   | ... | azd  |
|  2   | ... | iod  |
|  3   | ... | asd  |
|  3   | ... | aod  |
|  3   | ... | wsd  |
|  3   | ... | asi  |

我想更新表(或创建一个新表),所以看起来像这样:

| col1 | ... | colx |
---------------------
|  1   | ... | dfd  |
|      | ... | ajd  |
|      | ... | aad  |
|  2   | ... | azd  |
|      | ... | iod  |
|  3   | ... | asd  |
|      | ... | aod  |
|      | ... | wsd  |
|      | ... | asi  |

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

示例

Select col1 = case when RN=1 then concat('',col1) else '' end
      ,other
      ,colx
  From (
            Select *
                  ,RN = Row_Number() over (Partition By col1 order by colx) 
             From YourTable
       ) A
 Order by A.Col1,RN

<强>返回

enter image description here

答案 1 :(得分:0)

这样的东西?

DECLARE @MyTable TABLE
(
COL1 int,
COLX nvarchar(50)
)

INSERT INTO @MyTable(COL1,COLX)

VALUES
( 1  ,'dfd'),
( 1  ,'ajd'),
( 1  ,'aad'),
( 2  ,'azd'),
( 2  ,'iod'),
( 3  ,'asd'),
( 3  ,'aod'),
( 3  ,'wsd'),
( 3  ,'asi')

select ISNULL(newcol,'')as col1,COLX from (
Select COLX,cast(Case when rn = 1 then COL1  else null end as nvarchar(50)) 
as NewCOL from (
Select * ,Row_number() over(Partition by col1 order by col1 ) as rn from 
@MyTable
)x
)y

<强>结果:

enter image description here

答案 2 :(得分:0)

1.首先在表中添加一个新的标识列,以便我们可以将重复的重复值排序并更新为null:

alter table yourtable
add newcol int identity

2。如果要将col1中的重复值更新为null,则:

update yourtable
set col1 = null
where newcol not in (select min(newcol) from yourtable group by col1)

3.看你的结果:

select
     *
from
     yourtable
order by
     newcol asc

您不能删除已创建的标识列,但随后您将丢失订单..

如果您不想更新任何内容而只需要查询

1.您在表格上创建了​​新的标识栏后,您需要的是以下查询

select
     *
from
     yourtable
where
     newcol in (select min(newcol) from yourtable group by col1)