对每行中缺少值的行进行分组

时间:2014-12-01 10:51:14

标签: sql-server sql-server-2008 tsql

我在SQL Server 2008中有一个类似这样的表

FIELD1;FIELD2;FIELD3;FIELD4
-------------------------------
TEST1 ;AAAAAA;NULL  ;NULL
TEST1 ;NULL  ;BBBBBB;NULL
TEST1 ;NULL  ;NULL  ;CCCC
TEST2 ;XXXXXX;NULL  ;NULL
TEST2 ;NULL  ;YYYYYY;NULL
TEST2 ;NULL  ;NULL  ;ZZZZ
TEST3 ;UUUUUU;VVVVVV;NULL

我希望得到这样的结果:

FIELD1;FIELD2;FIELD3;FIELD4
TEST1 ;AAAAAA;BBBBBB;CCCC
TEST2 ;XXXXXX;YYYYYY;ZZZZ
TEST3 ;UUUUUU;VVVVVV;NULL

有没有很好的方法来实现这个目标?

2 个答案:

答案 0 :(得分:0)

静态解决方案在这里:

SELECT a.FIELD1,a.FIELD2,b.FIELD3,c.FIELD4
FROM YourTable a
LEFT JOIN YourTable b ON a.FIELD1 = b.FIELD1 AND b.FIELD3 IS NOT NULL
LEFT JOIN YourTable c ON a.FIELD1 = c.FIELD1 AND c.FIELD4 IS NOT NULL
WHERE a.FIELD2 IS NOT NULL

答案 1 :(得分:0)

实现它的一个简单方法是在select上使用子查询。

declare @MyTable table
(
    FIELD1 varchar(50)
   ,FIELD2 varchar(50)
   ,FIELD3 varchar(50)
   ,FIELD4 varchar(50)
)

insert into @MyTable values
('TEST1', 'AAAAAA', NULL    , NULL)
,('TEST1', NULL    , 'BBBBBB', NULL)
,('TEST1', NULL    , NULL    , 'CCCC')
,('TEST2', 'XXXXXX', NULL    , NULL)
,('TEST2', NULL    ,'YYYYYY', NULL)
,('TEST2', NULL    ,NULL    ,'ZZZZ')
,('TEST3', 'UUUUUU','VVVVVV', NULL)

select * from @MyTable t0


select t1.FIELD1
, (select top 1 t2.FIELD2 from @MyTable t2 where t2.FIELD2 is not null and t2.FIELD1 = t1.Field1)
, (select top 1 t3.FIELD3 from @MyTable t3 where t3.FIELD3 is not null and t3.FIELD1 = t1.Field1)
, (select top 1 t4.FIELD4 from @MyTable t4 where t4.FIELD4 is not null and t4.FIELD1 = t1.Field1)
 from @MyTable t1
  group by t1.FIELD1