Sql 配置单元查询优化
我的要求是获得有超过1个电子邮件id且类型为1的学生的id和姓名 我使用的查询如下Sql 配置单元查询优化,sql,performance,hive,query-optimization,hiveql,Sql,Performance,Hive,Query Optimization,Hiveql,我的要求是获得有超过1个电子邮件id且类型为1的学生的id和姓名 我使用的查询如下 select distinct b.id, b.name, b.email, b.type,a.cnt from ( select id, count(email) as cnt from ( select distinct id, email from table1 ) c group by id ) a join table1 b on a.id = b.id where b.
select distinct b.id, b.name, b.email, b.type,a.cnt
from (
select id, count(email) as cnt
from (
select distinct id, email
from table1
) c
group by id
) a
join table1 b on a.id = b.id
where b.type=1
order by b.id
请让我知道这是罚款或任何更简单的版本可用
Sample data is like:
id name email type
123 AAA abc@xyz.com 1
123 AAA acd@xyz.com 1
123 AAA ayx@xyz.com 3
345 BBB nch@xyz.com 1
345 BBB nch@xyz.com 1
678 CCC iuy@xyz.com 1
Expected Output:
123 AAA abc@xyz.com 1 2
123 AAA acd@xyz.com 1 2
345 BBB nch@xyz.com 1 1
678 CCC iuy@xyz.com 1 1
对于此要求,您可以使用
分组方式->having count()
select distinct b.id
, b.name,
, b.email
, b.type
from table1 b
where id in
(select distinct id from table1 group by email, id having count(email) > 1)
and b.type=1
order by b.id
您可以尝试使用count()函数的分析方式:
SELECT sub.ID, sub.NAME
FROM (SELECT ID, NAME, COUNT (*) OVER (PARTITION BY ID, EMAIL) cnt
FROM raw.crddacia_raw) sub
WHERE sub.cnt > 1 AND sub.TYPE = 1
我强烈建议使用窗口函数。但是,配置单元不支持作为窗口函数的count(distinct)
。有不同的方法来解决这个问题。一个是densite\u rank()
s的总和:
我希望这比你的版本有更好的性能。但是,值得测试不同的版本,看看哪个版本的性能更好(并且可以随时回来让其他人知道哪个更好)。还有一种方法使用collect\u set
并获取返回数组的大小来计算不同的电子邮件
演示:
结果:
id name email type cnt
123 AAA abc@xyz.com 1 2
123 AAA acd@xyz.com 1 2
345 BBB nch@xyz.com 1 1
678 CCC iuy@xyz.com 1 1
我们仍然需要在这里进行区分,因为解析函数不会像case345bbb那样删除重复项nch@xyz.com
这与您的查询非常相似,但在这里,我在初始步骤(在内部查询中)过滤数据,以便在较少的数据上不会发生连接
select distinct b.id,b.name,b.email,b.type,intr_table.cnt from table1 orig_table join
(
select a.id,a.type,count(a.email) as cnt from table1 as a where a.type=1 group by a
) intr_table on inter_table.id=orig_table.id,inter_table.type=orig_table.type
请提供数据和预期结果的代表性示例。如果同一id的同一电子邮件出现两次,此选项将不起作用。我想要>1封不同的电子邮件。但在我的情况下,它不是唯一的。这就是为什么我添加了一个带有distinctadded的子查询,从表1中选择distinct id
,如果相同的id有相同的电子邮件出现两次,此选项将无法正常工作。我想要>1个不同的emailsso,按id放置分区,email(我在上面的脚本中修改过)
id name email type cnt
123 AAA abc@xyz.com 1 2
123 AAA acd@xyz.com 1 2
345 BBB nch@xyz.com 1 1
678 CCC iuy@xyz.com 1 1
select distinct b.id,b.name,b.email,b.type,intr_table.cnt from table1 orig_table join
(
select a.id,a.type,count(a.email) as cnt from table1 as a where a.type=1 group by a
) intr_table on inter_table.id=orig_table.id,inter_table.type=orig_table.type