简体   繁体   中英

Move data from multiple rows to a single row in SQL Server

I have a table as show below-

F1  F2  F3  F4  
A   AB  NA  NA  
A   NA  BC  NA  
A   NA  NA  CD  
B   UV  NA  NA  
B   NA  WX  NA  
B   NA  NA  YZ  
C   ABC NA  NA  
C   NA  BCD NA  
C   NA  NA  XYZ  

I need to group by column F1 and choose values for consecutive columns not equal to 'NA'.

F1  F2  F3  F4  
A   AB  BC  CD  
B   UV  WX  YZ  
C   ABC BCD XYZ

I am using the following code but it is not working correctly.

 SELECT   F1
,MAX(ISNULL(F2 ,'')) as F2   
,MAX(ISNULL(F3 ,'')) as F3   
,MAX(ISNULL(F4 ,'')) as F4   
     FROM test
     group by F1;

Please help.

Try this:

 SELECT   F1
,MAX(ISNULL(NULLIF(F2, 'NA') ,'')) as F2   
,MAX(ISNULL(NULLIF(F3, 'NA') ,'')) as F3   
,MAX(ISNULL(NULLIF(F4, 'NA') ,'')) as F4   
     FROM test
     group by F1;

Note that the NULLIF will return NULL if the value of the first parameter is the same as the value of the second parameter.

选择F1,MAX(当F2 ='NA'THEN''ELSE F2 END时的情况)作为F2 MAX(当F3 ='NA'THEN时的情况''ELSE F3 END)AS F2 MAX(当F4 ='NA'THEN'的情况) 'ELSE F4 END)AS F2 from测试GROUP BY F1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM