在Access中我有四个表T1, T2, T3
和T4
,其中的字段为1到10.其中一个字段是" Field1"所以我有以下几点:
[T1].Field1, [T2].Field1, [T3].Field1, [T4].Field1
我想选择至少一个Field1相等的所有值。
换句话说,我想做一些像
这样的事情SELECT Field1,
Field2,
Field4,
Field5
FROM all the table before
WHERE [T1].Field1 = [T2].Field1
OR [T1].Field1 = [T3].Field1
OR [T1].Field1 = [T4].Field1
OR [T2].Field1 = [T3].Field1
OR [T2].Field1 = [T4].Field1
OR [T3].Field1 = [T4].Field1
-
我的主要困难是FROM
部分,因为SELECT
很好,我可以把所有我感兴趣的字段放在不同的表中,WHERE
也应该没问题,因为我可以说,正如我上面报道的那样。问题是在Access中使用FROM
命令选择数据。我相信它可以通过外部加入来完成,但我不知道如何实现它。
假设我有:
TABLE1
1 Field1: 0012
Field2: TEST
Field3: TEST3
2 Field1: 0010
Field2: TEST
Field3: TEST3
TABLE2
1 Field1: 0012
Field2: TEST2
Field3: TEST3
2 Field1: 0044
Field2: TEST
Field3: TEST3
TABLE3
1 Field1: 0012
Field2: TEST2
Field3: TEST3
2 Field1: 0044
Field2: TEST
Field3: TEST3
TABLE4
1 Field1: 0011
Field2: TEST2
Field3: TEST3
2 Field1: 0010
Field2: TEST
Field3: TEST3
3 Field1: 0044
Field2: TEST2
Field3: TEST3
此时我想生成输出
TABLE1.Field1 TABLE2.Field1 TABLE3.Field1 TABLE4.Field1 TABLE1.Field2 TABLE2.Field2 TABLE3.Field2 TABLE4.Field2
在这种情况下,第一行将是与Field1 0012相关联的一行:
0012 0012 0012 NULL TEST TEST2 TEST2 NULL
第二个到0010:
0010 NULL NULL 0010 TEST NULL NULL TEST
等等。 你能帮我正式化我的想法吗?
非常感谢
答案 0 :(得分:1)
首先将所有记录与UNION ALL
粘在一起,保留表名。然后聚合每field1
并使用传统聚合来获取单个字段。使用HAVING
仅显示包含多个表条目的field1
:
select
max(iif(table_name = 'TABLE1', field1, null)) as table1_field1,
max(iif(table_name = 'TABLE2', field1, null)) as table2_field1,
max(iif(table_name = 'TABLE3', field1, null)) as table3_field1,
max(iif(table_name = 'TABLE4', field1, null)) as table4_field1,
max(iif(table_name = 'TABLE1', field2, null)) as table1_field2,
max(iif(table_name = 'TABLE2', field2, null)) as table2_field2,
max(iif(table_name = 'TABLE3', field2, null)) as table3_field2,
max(iif(table_name = 'TABLE4', field2, null)) as table4_field2,
max(iif(table_name = 'TABLE1', field3, null)) as table1_field3,
max(iif(table_name = 'TABLE2', field3, null)) as table2_field3,
max(iif(table_name = 'TABLE3', field3, null)) as table3_field3,
max(iif(table_name = 'TABLE4', field3, null)) as table4_field3
from
(
select 'TABLE1' as table_name, field1, field2, field3 from table1
union all
select 'TABLE2' as table_name, field1, field2, field3 from table2
union all
select 'TABLE3' as table_name, field1, field2, field3 from table3
union all
select 'TABLE4' as table_name, field1, field2, field3 from table4
) alldata
group by field1
having count(*) > 1;