在SQL Server中组织表以删除NULL值并从相同级别开始

时间:2017-04-01 04:33:36

标签: sql sql-server

我想在SQL Server中格式化表数据。 目前我的表格显示数据为: -

enter image description here

我想修改表数据以显示为: -

enter image description here

请告诉我需要进行更改的查询。

1 个答案:

答案 0 :(得分:4)

如果您只想以这种方式查询数据,那么简单的聚合就足够了。

select code,
    max(val1) as val1,
    max(val2) as val2,
    max(val3) as val3
from your_table
group by code;

如果您想修改表格中的数据,即更新和删除行以获得最终结果,一种方法是使用MERGE

with cte as (
    select t.*,
        row_number() over (partition by code order by code) as seqnum,
        max(val1) over (partition by code) as max_val1,
        max(val2) over (partition by code) as max_val2,
        max(val3) over (partition by code) as max_val3
    from your_table t
)
merge into cte as t
using cte as s
on (
    t.code = s.code
    and t.seqnum = s.seqnum
    and t.seqnum = 1
)
when matched then update set 
    t.val1 = s.max_val1,
    t.val2 = s.max_val2,
    t.val3 = s.max_val3
when not matched by source then delete;

Demo