将4个表中的数据合并为一个列/字段

时间:2013-01-25 12:39:02

标签: sql ms-access ms-access-2010

我需要在MS Access 2010中创建一个查询,该查询将来自一个列中4个不同表的数据组合在一起。

表格定义如下;

Table 1: date, country, channel, calls_in
Table 2: date, country, channel, calls_out
Table 3: date, country, channel, email
Table 4: date, country, channel, chat

查询应如下所示:

Query 1: Date, country, channel, contacts 

联系人列应结合适当的日期,国家/地区和频道的4种联系方式(即来电/退出,电子邮件和聊天)。

所有4个表都有相同的日期和国家/地区。频道特定于每个表格。

我一直试图完成这项任务,但无法理解它。

3 个答案:

答案 0 :(得分:2)

使用UNION(隐式不同)或UNION ALL

SELECT date, country, channel, 'calls_in' AS ContactType, calls_in AS ContactData
FROM table1
UNION ALL
SELECT date, country, channel, 'calls_out', calls_out        
FROM table2
UNION ALL
SELECT date, country, channel, 'email', email
FROM table3
UNION ALL
SELECT date, country, channel, 'chat', chat
FROM table4;

这将为您提供四个表中的所有数据,其中包含ContactTypecalls_incalls_out和{{1}三种类型的新列email与他们的数据结合在一起。

答案 1 :(得分:2)

你可能会在此之后:

SELECT
  all_contacts.date,
  all_contacts.country,
  all_contacts.channel,
  "calls in: " & [calls_in] & ", calls out: " & [calls_out] & ", email: " & [email] & ", chat " & [chat] AS contacts
FROM
  ((((select date, country, channel from [Table 1] union
      select date, country, channel from [Table 2] union
      select date, country, channel from [Table 3] union
      select date, country, channel from [Table 4])  AS all_contacts
  LEFT JOIN [Table 1] ON (all_contacts.channel = [Table 1].channel) AND (all_contacts.country = [Table 1].country) AND (all_contacts.date = [Table 1].date))
  LEFT JOIN [Table 2] ON (all_contacts.channel = [Table 2].channel) AND (all_contacts.country = [Table 2].country) AND (all_contacts.date = [Table 2].date))
  LEFT JOIN [Table 3] ON (all_contacts.channel = [Table 3].channel) AND (all_contacts.country = [Table 3].country) AND (all_contacts.date = [Table 3].date))
  LEFT JOIN [Table 4] ON (all_contacts.channel = [Table 4].channel) AND (all_contacts.country = [Table 4].country) AND (all_contacts.date = [Table 4].date);

由于MS-Access不支持FULL OUTER JOINS,并且没有像GROUP_CONCAT这样的聚合函数,所以我还要加入一个包含所有日期,国家和频道的UNION子查询对于每个表格,然后我将所有联系人(calls_in,calls_out,email和chat)组合到一个单元格中。

答案 2 :(得分:1)

我想略微改进Mahmoud的答案:

SELECT date, country, channel, calls_in, 'Calls_in' as ContactType  FROM table1
UNION ALL
SELECT date, country, channel, calls_out, 'Calls_out' as ContactType FROM table2
UNION ALL
SELECT date, country, channel, email, 'email' as ContactType FROM table3
UNION ALL
SELECT date, country, channel, chat, 'Calls_in' as ContactType FROM table4;

但我必须说,显然数据库可以进行一些规范化。如果您可以修改数据库,您可以非常轻松地将所有数据放在一个表中,并且只需一个跟踪您使用的通信类型的字段。