我有两张数据表。两个表都有一个CUSTOMER_ID
列(数字)。我正在尝试获取CUSTOMER_ID
和的所有唯一值的列表,知道CUSTOMER_ID
是否存在于两个表中,还是只存在一个(以及哪一个)。< / p>
我可以轻松获取唯一CUSTOMER_ID
:
SELECT tblOne.CUSTOMER_ID
FROM tblOne.CUSTOMER_ID
UNION
SELECT tblTwo.CUSTOMER_ID
FROM tblTwo.CUSTOMER_ID
我不能只为SELECT
statemtn添加标识符列(例如:SELECT tblOne.CUSTOMER_ID, "Table1" AS DataSource
),因为这些记录不会是唯一的,它将获得两组数据。
我觉得我需要在此查询中的其他位置添加它,但我不确定如何。
对于联合查询输出,我需要一个额外的列,可以告诉我我看到的唯一值是否存在于:(1)两个表,(2)表一或(3)表二。
答案 0 :(得分:12)
如果CUSTOMER_ID出现在两个表中,那么我们将不得不随意选择要调用源的表。在这种情况下,以下查询使用“tblOne”作为[SourceTable]:
SELECT
CUSTOMER_ID,
MIN(Source) AS SourceTable,
COUNT(*) AS TableCount
FROM
(
SELECT DISTINCT
CUSTOMER_ID,
"tblOne" AS Source
FROM tblOne
UNION ALL
SELECT DISTINCT
CUSTOMER_ID,
"tblTwo" AS Source
FROM tblTwo
)
GROUP BY CUSTOMER_ID
答案 1 :(得分:3)
select customer_id,
iif(min(which) = max(which), min(which), "both") as DataSource
from (select customer_id, "tblone" as which
from tblOne
UNION ALL
select customer_id, "tbltwo" as which
from tblTwo
) t
group by customer_id
答案 2 :(得分:2)
我们可以添加一个带有整数数据类型的标识符列,然后执行外部查询:
SELECT
CUSTOMER_ID,
sum(Table)
FROM
(
SELECT
DISTINCT CUSTOMER_ID,
1 AS Table
FROM tblOne
UNION
SELECT
DISTINCT CUSTOMER_ID,
2 AS Table
FROM tblTwo
)
GROUP BY CUSTOMER_ID`
所以如果&#34;总和是1&#34;然后它来自tablOne,如果它是2那么它来自tableTwo,如果它是3然后它存在于两者
如果你想在联合中添加第3个表,那么给它一个值4,这样你就可以为每个组合添加一个唯一的总和