SQL用每个组的第一个数据填充空白行

问题描述:

这是我原始数据的结果集。 我想要的是填写下列空白行,列名为 的名称,每组的名字。SQL用每个组的第一个数据填充空白行

在这个例子中rowid 1881和1879应该填充 MAR ROXAS和1881-1887填充到RODRIGO DUTERTE等等。

enter image description here

理想的方式是lag(ignore nulls),但SQL Server不支持。相反,您可以使用两个级别的窗口函数:

select max(name) over (partition by name_rowid) as new_name 
from (select t.*, 
      max(case when name is not null then rowid end) over (order by rowid) as name_rowid 
     from billtrans t 
    ) t; 

上述工作在SQL Server 2012+中。在SQL Server 2008中,可以使用更少的有效的方法,如outer apply:您也可以此语用类似结构的相关子查询

select t.*, t2.name as new_name 
from billtrans t outer apply 
    (select top 1 t2 
     from billtrans t2 
     where t2.rowid <= t.rowid and t2.name is not null 
     order by t2.rowid desc 
    ) t2; 

+0

请使用我的表trans_Bills重新构建您的查询。我在SQL Server 2008中尝试使用它时遇到订单功能中的错误 –

+0

在SQL Server 2008上无法使用 –

+0

select t。*,t2.name as new_name from trans_Bills t外部应用 (select top 1 t2 来自trans_Bills t2 其中t2.rowid