在两列中联合两个具有不同值的select语句

时间:2014-08-21 15:36:01

标签: sql tsql union

我有两个选择语句:

SELECT '1' AS ID , 'JOHN' AS SURNAME, NULL AS FIRSTNAME
SELECT '1' AS ID,  NULL AS SURNAME, 'BLOGGS' AS FIRSTNAME

如何以两行合二为一的方式在结果中得到这个?

1 | JOHN | BLOGGS

1 个答案:

答案 0 :(得分:1)

您可以使用union all和聚合:

执行此操作
SELECT ID, MAX(SURNAME) as SURNAME, MAX(FIRSTNAME) as FIRSTNAME
FROM (SELECT '1' AS ID , 'JOHN' AS SURNAME, NULL AS FIRSTNAME
      UNION ALL
      SELECT '1' AS ID,  NULL AS SURNAME, 'BLOGGS' AS FIRSTNAME
     ) t
GROUP BY ID;