有查询可以做到这一点吗?

问题描述 投票:-5回答:1

表:

col1       col2   col3    col4      col5    col6      col7   col8   col9
-----------------------------------------------------------------------------
2018-02-22  A      B       C          D     625.2      E       K    448
2018-02-22  A      B       C          D     625.2      F       L    5.35
2018-02-22  A      B       C          D     625.2      G       M    35.71
2018-02-22  A      B       C          D     625.2      H       N    87.39
2018-02-22  A      B       C          D     625.2      I       O    25.11
2018-02-22  A      B       C          D     625.2      J       P    33.93
2018-02-22  A1     B1      C1         D1    14849.5    E1      K1   13294.21
2018-02-22  A1     B1      C1         D1    14849.5    F1      L1   427.03
2018-02-22  A1     B1      C1         D1    14849.5    G1      M1   631.85
2018-02-22  A1     B1      C1         D1    14849.5    H1      N1   326.07
2018-02-22  A1     B1      C1         D1    14849.5    I1      O1   146.36
2018-02-22  A1     B1      C1         D1    14849.5    J1      P1   6.86

结果:

col1       col2   col3    col4      col5    col6      col7   col8   col9
-----------------------------------------------------------------------------
2018-02-22  A      B       C          D     625.2      E       K    448
2018-02-22                                  625.2      F       L    5.35
2018-02-22                                  625.2      G       M    35.71
2018-02-22                                  625.2      H       N    87.39
2018-02-22                                  625.2      I       O    25.11
2018-02-22                                  625.2      J       P    33.93
2018-02-22  A1     B1      C1         D1    14849.5    E1      K1   13294.21
2018-02-22                                  14849.5    F1      L1   427.03
2018-02-22                                  14849.5    G1      M1   631.85
2018-02-22                                  14849.5    H1      N1   326.07
2018-02-22                                  14849.5    I1      O1   146.36
2018-02-22                                  14849.5    J1      P1   6.86
sql sql-server
1个回答
2
投票

如果您的表中有任何我们可以对数据进行排序的唯一列,那么我们可以使用LAG函数,如下所示 -

declare @x table (id int, col1 varchar(10))

insert into @x (id, col1)
select 1, 'A' union all
select 2, 'A' union all
select 3, 'A' union all
select 4, 'A' union all
select 5, 'B' union all
select 6, 'B'

select
    id,
    col1,
    (case when col1 = lag(col1) over (order by id asc) then '' else col1 end) as NewCol
from @x

输出 -

id  col1    NewCol
1   A       A
2   A   
3   A   
4   A   
5   B       B
6   B   
© www.soinside.com 2019 - 2024. All rights reserved.