2011-02-28 4 views
2

데이터가있는 큰보기가 있습니다. 관련 정보가 포함 된 두 개의 열에 대해서는 공백이 없도록 데이터를 축소하고 싶습니다. 예를 들어 내가 말하는 의미가 더 좋을 것입니다.두 열의 행 축소

ID Title Column1 Column2 
    -11 Row1 NULL Anna 
    -11 Row1 Lars NULL 
    -10 Row2 NULL Thomas 
    -9 Row3 Paul NULL 
    -7 Row4 Gerald NULL 
    -6 Row5 NULL Micha 
    -6 Row5 NULL Hans 
    -6 Row5 NULL Robert 
    -6 Row5 Rene NULL 
    -6 Row5 Olga NULL 
    -6 Row5 Markus NULL 
    -6 Row5 Klaus NULL 
    -6 Row5 Sascha NULL 

그리고 나는 공백을 축소하고 싶습니다, 그래서 다음과 같습니다

ID Title Column1 Column2 
    -11 Row1 Lars Anna 
    -10 Row2 NULL Thomas 
    -9 Row3 Paul NULL 
    -7 Row4 Gerald NULL 
    -6 Row5 Rene Micha 
    -6 Row5 Olga Hans 
    -6 Row5 Markus Robert 
    -6 Row5 Klaus NULL 
    -6 Row5 Sascha NULL 

는 당신의 도움을 주셔서 감사합니다!

답변

1
declare @t table (ID int, Title varchar(10), Column1 varchar(10), Column2 varchar(10)) 
insert @t select 
    -11 ,'Row1', NULL ,'Anna' union all select 
    -11 ,'Row1', 'Lars' , NULL union all select 
    -10 ,'Row2', NULL ,'Thomas' union all select 
    -9 ,'Row3', 'Paul' , NULL union all select 
    -7 ,'Row4', 'Gerald', NULL union all select 
    -6 ,'Row5', NULL ,'Micha' union all select 
    -6 ,'Row5', NULL ,'Hans' union all select 
    -6 ,'Row5', NULL ,'Robert' union all select 
    -6 ,'Row5', 'Rene' ,NULL union all select 
    -6 ,'Row5', 'Olga' ,NULL union all select 
    -6 ,'Row5', 'Markus' ,NULL union all select 
    -6 ,'Row5', 'Klaus' ,NULL union all select 
    -6 ,'Row5', 'Sascha' ,NULL 

-- the above merely sets up a table variable @t. Replace @t in the below portion 
-- with your table name. Below is the actual query 

;with a as (
select *, 
rn1=row_number() over (partition by title order by column1) 
from @t 
where column1 is not null 
), b as (
select *, 
rn2=row_number() over (partition by title order by column2) 
from @t 
where column2 is not null 
) 
select a.id, a.title, a.column1, b.column2, * 
from a 
full join b 
on a.title = b.title and a.rn1=b.rn2 
where coalesce(a.column1, b.column2) is not null 
order by coalesce(a.title, b.title), a.rn1, b.rn2 
+0

SQL 서버 2005 + – RichardTheKiwi

+0

는 당신의 도움을 주셔서 감사합니다! 그것은 정말로 나를 구했다! – Paul

-1
select id, title, column1, column2 
from my_view 
where column1 is not null and column2 is not null 
union 
select max(id) as id, max(title) as title, column1, column2 
from my_view as v1 
inner join my_view as v2 on v1.id = v2.id 
where column1 is null or column2 is null 
group by column1, column2 

order by id, title, column1, column2 
관련 문제