组合两行,其中1列具有值,而另一列为null

时间:2013-12-29 06:33:22

标签: sql-server-2008 tsql row

我正在尝试将两行(重复)组合在一起

1)第一排为空,第二排为零(或副-A-Versa) 2)两行都为空。

我需要将这两行组合在一起产生1行,其中有该列的值(如果任何一行存在)或者为null。

例如。

issue

需要转换为 Result

我为相同的数据设置了SQL Fiddle here。如果您需要更多信息,请与我们联系。

到目前为止,我已经尝试过使用Full Outer Join(对于那么多有空值和东西的列不起作用)和Pivot(我不确定它是否适合这个问题)。

SELECT A.EmployeeID, A.PostEditDate, 
A.In1
, A.Out2, A.In3, A.Out4, A.Out5, A.Out6, A.Out7, A.Out8, A.Out9, A.Out10  FROM #TempTableRV A
full outer JOIN #TempTableRV B
On A.EmployeeID = B.EmployeeID AND A.PostEditDate = B.PostEditDate
where 
A.PostEditDate = '2007-06-19 00:00:00.000' 
AND 
A.EmployeeID = 25690 and A.In1 IS NULL AND B.In1 IS NULL 

3 个答案:

答案 0 :(得分:2)

SELECT

EmployeeID,
MAX(PostEditDate) AS PostEditDate,
MAX(In1) AS In1,
MAX(Out2) AS Out2,
MAX(In3) AS In3,
MAX(Out4) AS Out4,
MAX(Out5) AS Out5,
MAX(Out6) AS Out6,
MAX(Out7) AS Out7,
MAX(Out8) AS Out8,
MAX(Out9) AS Out9,
MAX(Out10) AS Out10

FROM

#TempTableRV

GROUP BY
EmployeeID

答案 1 :(得分:1)

试试这个

SELECT DISTINCT EmployeeId,PostEditDate,
(SELECT In1 FROM TempTableRV WHERE T.EmployeeId=EmployeeId AND T.PostEditDate=PostEditDate AND In1 IS NOT NULL) AS In1, 
(SELECT Out2 FROM TempTableRV WHERE T.EmployeeId=EmployeeId AND T.PostEditDate=PostEditDate AND Out2 IS NOT NULL) AS Out2, 
(SELECT In3 FROM TempTableRV WHERE T.EmployeeId=EmployeeId AND T.PostEditDate=PostEditDate AND In3 IS NOT NULL) AS In3, 
(SELECT Out4 FROM TempTableRV WHERE T.EmployeeId=EmployeeId AND T.PostEditDate=PostEditDate AND Out4 IS NOT NULL) AS Out4,
Out5,Out6,Out7,Out8,Out9,Out10
FROM TempTableRV AS T

如果需要,您可以对其余列(Out5,Out6,Out7,Out8,Out9,Out10)执行此操作。

答案 2 :(得分:0)

我会创建一个带有固定/匹配值的新临时表,然后更新它以设置有时为null的值。