SQL,仅将两个表组合为不同的值(仅基于三个字段,而不是整行)

时间:2016-04-21 15:21:28

标签: sql duplicates union sql-except

我试图合并三个表,应用程序,音频,视频。他们都有相同的架构,但有重复的'在音频和视频中。视频中的条目始终也会显示在音频中。我将重复项放在引号中,因为整行不是重复的,而是基于三个字段。

音频表

   **Calls   | StartTime    | EndTime       | Quality | CallType**
      John   | 3/15/16 8:01 | 3/15/16 9:01  |   0     |   Audio
      Mary   | 3/15/16 9:35 | 3/15/16 10:34 |   1     |   Audio

视频表

   **Calls   | StartTime     | EndTime       | Quality | CallType**
      John   | 3/15/16 8:01  | 3/15/16 9:01  |   1     |   Video
      Sue    | 3/15/16 11:32 | 3/15/16 11:50 |   0     |   Video

申请表

   **Calls   | StartTime     | EndTime       | Quality | CallType**
      Matt   | 3/15/16 7:31  | 3/15/16 8:01  |   1     |   App
      Bill   | 3/15/16 1:32  | 3/15/16 2:50  |   0     |   App

我希望将它们合并到一个表中,当有重复项时,它会保留Video中的数据 - 所以你看到John只显示一次,具有来自Video表的质量和calltype:

   **Calls   | StartTime     | EndTime       | Quality | CallType**
      Mary   | 3/15/16 9:35  | 3/15/16 10:34 |   1     |   Audio
      John   | 3/15/16 8:01  | 3/15/16 8:01  |   1     |   Video
      Sue    | 3/15/16 11:32 | 3/15/16 11:50 |   0     |   Video
      Matt   | 3/15/16 7:31  | 3/15/16 8:01  |   1     |   App
      Bill   | 3/15/16 1:32  | 3/15/16 2:50  |   0     |   App

我试图使用EXCEPT和UNION,选择音频中不会显示在视频中的所有行,然后加入视频,但因为它看到它们是唯一的,因为calltype总是不同,质量可能会有所不同。

   SELECT Calls, StartTime, EndTime, Quality, CallType
   FROM Audio

   EXCEPT
   SELECT Calls, StartTime, EndTime, Quality, CallType
   FROM Video

   UNION
   SELECT Calls, StartTime, EndTime, Quality, CallType
   FROM Video

   UNION
   SELECT Calls, StartTime, EndTime, Quality, CallType
   FROM Application

1 个答案:

答案 0 :(得分:1)

嗯,我会这样做:

SELECT Calls, StartTime, EndTime, Quality, CallType
FROM Application
UNION ALL
SELECT Calls, StartTime, EndTime, Quality, CallType
FROM Video
UNION ALL
SELECT Calls, StartTime, EndTime, Quality, CallType
FROM Audio a
WHERE NOT EXISTS (SELECT 1
                  FROM Video v
                  WHERE v.Calls = a.Calls and v.StartTime = a.StartTime and v.EndTime = a.EndTime
                 );

注意:

  • 使用UNION ALL代替UNION,除非您故意要承担删除重复项的开销。
  • 这适用于任何数据库;它使用标准SQL。
  • 小心时代。你确定它们完全相同,直到毫秒?