Search code examples
sqlhivesubqueryinner-joinhaving-clause

Join results using group by clause


How do i join the below 2 queries Query 1

select phn,count(*) from table 1 
group by phn
having count(*)>20 

with the above result i need to join table 2 to get ids

Query 2

select count(distinct id) from table 2 
where (result_of_query1).phn=table 2.phn

Solution

  • You can join as follows:

    select count(distinct id)
    from table2 t2
    inner join (
        select phn
        from table1 
        group by phn
        having count(*) > 20 
    ) t1 on t1.phn = t2.phn