如何基于常见值合并数据库行?

时间:2014-07-22 04:58:56

标签: sql database merge hiveql

我有这样一张桌子:

Col1   Col2   Col3   Col4   Col5
====   ====   ====   ====   ====
 A1     B1     C1    null   null
 A1    null    C1    null    E1
 A1     B2    null    D1     E2
 A1    null    C2    null    E2

如何合并信息以便我最终得到:

Col1   Col2   Col3   Col4   Col5
====   ====   ====   ====   ====
 A1     B1     C1    null    E1
 A1     B2     C2     D1     E2

SQL会为我做什么?请注意,两个C1允许合并前两行,并且两个E2允许最后两行合并。

1 个答案:

答案 0 :(得分:1)

希望这会有所帮助..

CREATE TABLE #LocalTempTable(
col1 varchar(50) ,
col2 varchar(50) NuLL, 
col3 varchar(50) NuLL,
col4 varchar(50) NuLL, 
col5 varchar(50) NuLL)

insert into #LocalTempTable values ( 'A1', 'B1','C1',NULL,NULL);
insert into #LocalTempTable values ( 'A1', NULL,'C2',NULL,'E1');
insert into #LocalTempTable values ( 'A1', 'B2',NULL,'D1','E2');
insert into #LocalTempTable values ( 'A1', NULL,'C2',NULL,'E2');


select * from #LocalTempTable


 --A1     B1     C1    null    E1
 --A1     B2     C2     D1     E2
 select  *from(
select  ROW_NUMBER() over  ( order by lc1.col1  ) as ID ,
lc1.col1
,lc1.col2
,lc1.col3
,lc1.col4
,lc2.col5
 from #LocalTempTable lc1 inner join #LocalTempTable lc2 on lc2.col1=lc1.col1 ) as c where ID=5
 union 

 select  *from(
select  ROW_NUMBER() over  ( order by lc1.col1  ) as ID ,
lc1.col1
,isnull(lc1.col2,lc2.col2) as col2
,isnull(lc2.col3,lc1.col3) as col3
,isnull(lc1.col4,lc2.col4) as col4
,lc2.col5
 from #LocalTempTable lc1 inner join #LocalTempTable lc2 on lc2.col1=lc1.col1 ) as c where ID=10