0

我有三个具有相同列的表,我需要将它们合并到一个表中。一些 ID 出现在多个表中,我需要首先使用编号最小的表中的 ID,并在任何后续表中忽略该 ID。请注意,只有 ID 相同,表之间没有任何重复的行。

举个例子,这三个表需要转换为最终表:

**Table 1**
+----+----+----+
| ID | C1 | C2 |
+----+----+----+
| 01 | AA | BB |
| 02 | CC | DD |
| 03 | EE | FF |
+----+----+----+

**Table 2**
+----+----+----+
| ID | C1 | C2 |
+----+----+----+
| 03 | GG | HH |
| 04 | II | JJ |
| 05 | KK | LL |
+----+----+----+

**Table 3**
+----+----+----+
| ID | C1 | C2 |
+----+----+----+
| 01 | MM | NN |
| 04 | OO | PP |
| 06 | QQ | RR |
+----+----+----+

**Resulting Table**
+----+----+----+
| ID | C1 | C2 |
+----+----+----+
| 01 | AA | BB |
| 02 | CC | DD |
| 03 | EE | FF |
| 04 | II | JJ |
| 05 | KK | LL |
| 06 | QQ | RR |
+----+----+----+

我对使用左连接和“IS NULL”条件的解决方案有一个模糊的想法,但这可能会很快变得复杂,尤其是在表数量增加的情况下。

有没有办法只在一列上指定重复项,而不是在整行上?

4

2 回答 2

2

由于您使用的是 Access,因此您可以使用 FIRST 功能,我认为您只需要这个:

SELECT ID, First(C1) As C1, First(C2) as C2
FROM (
  SELECT * FROM Table1 UNION SELECT * FROM Table2 UNION SELECT * FROM Table3 )
GROUP BY ID
于 2012-11-08T16:19:07.810 回答
1

如果 NULL 值不计算在内,则可以应用此逻辑:

  • 获取 3 个表中存在的所有 ID(这是联合部分)
  • 左连接所有表,并使用 COALESCE,找到每列的第一个非空值

使用权微软 SQL:

select ids.ID, COALESCE(t1.C1,t2.C1,t3.C1) C1, COLAESCE(t1.C2,t2.C2,t3.C2) C2 
from
(SELECT ID FROM Table1
UNION
SELECT ID FROM Table2
UNION
SELECT ID FROM Table3) AS ids
left join Table1 t1 on ids.id=t1.id
left join Table2 t2 on ids.id=t2.id
left join Table3 t3 on ids.id=t3.id

但遗憾的是 Access不支持 COALESCE ......它有 NZ:

select ids.ID, NZ(NZ(t1.C1,t2.C1),t3.C1) C1, NZ(NZ(t1.C2,t2.C2),t3.C2) C2 
from
(SELECT ID FROM Table1
UNION
SELECT ID FROM Table2
UNION
SELECT ID FROM Table3) AS ids
left join Table1 t1 on ids.id=t1.id
left join Table2 t2 on ids.id=t2.id
left join Table3 t3 on ids.id=t3.id

(虽然我目前无法测试它没有手头的 MS Access)

旁注:在 Oracle 中,您可以这样做(我不想删除它):

select ids.ID, NVL(NVL(t1.C1,t2.C1),t3.C1) C1, NVL(NVL(t1.C2,t2.C2),t3.C2) from
(SELECT ID FROM Table1
UNION
SELECT ID FROM Table2
UNION
SELECT ID FROM Table3) ids
left join Table1 t1 on ids.id=t1.id
left join Table2 t2 on ids.id=t2.id
left join Table3 t3 on ids.id=t3.id

然而,如果 NULL 值被认为是有效的,那就有点问题了,因为MS Access 不支持 CASE-WHEN 语句——除非在 VBA 中......

在 Oracle 中,这样做可以:

select ids.ID,
CASE WHEN t1.ID IS NOT NULL THEN t1.C1 
     WHEN t1.ID IS NULL AND t2.ID IS NOT NULL THEN t2.C1
     ELSE t3.C1 END C1,
CASE WHEN t1.ID IS NOT NULL THEN t1.C2 
     WHEN t1.ID IS NULL AND t2.ID IS NOT NULL THEN t2.C2
     ELSE t3.C2 END C2
from
(SELECT ID FROM Table1
UNION
SELECT ID FROM Table2
UNION
SELECT ID FROM Table3) AS ids
left join Table1 t1 on ids.id=t1.id
left join Table2 t2 on ids.id=t2.id
left join Table3 t3 on ids.id=t3.id
于 2012-11-08T15:28:03.377 回答