2

我需要在 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 种联系人类型(即 call_in/out、电子邮件和聊天)。

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

我一直在努力完成这项工作,但无法理解它。

4

3 回答 3

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;

这将为您提供四个表中的所有数据,ContactType以及三种类型的新列calls_in、 、calls_outemailchat与它们的数据组合在一起。

于 2013-01-25T12:42:41.163 回答
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、电子邮件和聊天)合并到一个单元格中。

于 2013-01-25T12:47:57.347 回答
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;

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

于 2013-01-25T12:51:23.623 回答