[英]SQL count of distinct union
I have a query that captures customer ids from three tables (each table is a different contact method).我有一个从三个表中捕获客户 ID 的查询(每个表都是不同的联系方式)。 I want to get the count of distinct customer ids after the unions.
我想在工会之后获得不同客户 ID 的数量。
The SQL statement below is working and returns a list of unique customer ids (no dups):下面的 SQL 语句正在运行并返回唯一客户 ID 的列表(无重复):
SELECT DISTINCT customer_id
FROM email_contact
WHERE info_id = 1
AND status = 'SENT'
UNION
SELECT DISTINCT customer_id
FROM call_contact
WHERE info_id = 1
AND status = 'CALLED'
UNION
SELECT DISTINCT customer_id
FROM mail_contact
WHERE info_id = 1
AND status = 'MAILED'
From that query I want a count of customers, but my attempts to wrap the query in a select count keep producing syntax errors.从那个查询中,我想要一个客户计数,但我尝试将查询包装在一个选择计数中,但一直产生语法错误。 How can wrap the unions to provide me with a count of the clients?
如何包装工会以向我提供客户数量?
I would recommend:我会推荐:
SELECT COUNT(DISTINCT customer_id)
FROM (
SELECT customer_id FROM email_contact WHERE info_id = 1 AND status = 'SENT'
UNION ALL SELECT customer_id FROM call_contact WHERE info_id = 1 AND status = 'CALLED'
UNION ALL SELECT customer_id FROM mail_contact WHERE info_id = 1 AND status = 'MAILED'
) t
I removed the DISTINCT
and I changed the UNION
s to UNION ALL
, so the database just gathers all the rows from the 3 union members without attempting to manage duplicates (this is fast).我删除了
DISTINCT
并将UNION
s更改为UNION ALL
,因此数据库只收集来自 3 个联合成员的所有行,而不尝试管理重复项(这很快)。 Then, you can use COUNT(DISTINCT ...)
in the outer query.然后,您可以在外部查询中使用
COUNT(DISTINCT ...)
。
You can wrap it like this你可以这样包裹
SELECT COUNT(*)
FROM
( SELECT DISTINCT customer_id
FROM email_contact
WHERE info_id = 1
AND status = 'SENT'
UNION
SELECT DISTINCT customer_id
FROM call_contact
WHERE info_id = 1
AND status = 'CALLED'
UNION
SELECT DISTINCT customer_id
FROM mail_contact
WHERE info_id = 1
AND status = 'MAILED') t1
Is this what you ant?这是你的蚂蚁吗?
SELECT COUNT(*)
FROM ((SELECT customer_id
FROM email_contact
WHERE info_id = 1 AND status = 'SENT'
) UNION -- on purpose to remove duplicates
(SELECT customer_id
FROM call_contact
WHERE info_id = 1 AND status = 'CALLED'
) UNION
(SELECT customer_id
FROM mail_contact
WHERE info_id = 1 AND status = 'MAILED'
)
) c;
Note that all your DISTINCT
s are unnecessary because UNION
removes duplicates.请注意,您的所有
DISTINCT
都是不必要的,因为UNION
会删除重复项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.