我有多个select语句涉及许多表和联接。所有select语句都具有相同的标题。我正在尝试将所有这些组合成一个结果集。那么哪种方法更好的SQL UNION
或MERGE
?
我知道UNION是A + B.因此,如果表A中的列为NULL并且它在表B中具有值,那么UNION会给我两行吗?所以,如果我想根据id将所有行组合成一行,我应该使用MERGE吗?我可以选择在SQL或SSIS中执行此操作。
SELECT ID, NAME, VitalName as VitalName FROM TABLE A
UNION
SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B
表A
+----+------+-----------+
| ID | Name | VitalName |
+----+------+-----------+
| 1 | AAA | HeartRate |
| 2 | | Systolic |
| 3 | | Diastolic |
+----+------+-----------+
表B
+----+------+---------------+
| ID | Name | VitalReadings |
+----+------+---------------+
| 1 | AAA | HeartRate |
| 2 | BBB | Systolic |
+----+------+---------------+
预期结果
+----+------+---------------+
| ID | Name | VitalName |
+----+------+---------------+
| 1 | AAA | HeartRate |
| 2 | BBB | Systolic |
| 3 | | Diastolic |
+----+------+---------------+
答案 0 :(得分:4)
UNION
和MERGE
完全不同的概念,都不能解决您的问题。但可以使用FULL JOIN
来实现此目的。
DECLARE @TableA TABLE (ID INT, Name VARCHAR(10), VitalName VARCHAR(10))
INSERT INTO @TableA VALUES
(1,'AAA','HeartRate'),
(2,NULL,'Systolic'),
(3,NULL,'Diastolic')
DECLARE @TableB TABLE ( ID INT, Name VARCHAR(10), VitalReadings VARCHAR(10))
INSERT INTO @TableB VALUES
(1,'AAA','HeartRate'),
(2,'BBB','Systolic')
SELECT
A.ID,
COALESCE(A.Name, B.Name) Name,
COALESCE(A.VitalName, B.VitalReadings) VitalName
FROM
@TableA A
FULL JOIN @TableB B ON A.ID = B.ID
结果:
ID Name VitalName
----------- ---------- ----------
1 AAA HeartRate
2 BBB Systolic
3 NULL Diastolic
答案 1 :(得分:1)
GROUP BY
UNION
的结果。使用MAX()
返回NAME:
select ID, MAX(NAME), VitalName
from
(
SELECT ID, NAME, VitalName as VitalName FROM TABLE A
UNION ALL
SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B
) dt
group by ID, VitalName
答案 2 :(得分:0)
使用union,然后使用select distinct删除重复。
e.g。 SELECT DISTINCT * FROM (SELECT ID, NAME, VitalName as VitalName FROM TABLE_A
UNION SELECT ID, NAME, VitalReadings as VitalName FROM TABLE_B) as TABLE_C