0

I want to merge the following queries to get the answer I want. But I don't seem to get it right.

Query 1:

select a.idlisting, count(p.idpostulant) as Total_postulants
from postulations p
inner join listings a on p.idlisting = a.idlisting
where a.idate >= '2014-07-01'
and a.idate < '2014-08-01'
group by a.idlisting
having total_postulants > 500

With the answer I get from the first query I complete the idlisting clause

**Query 2:**

select count(distinct p.idpostulant)
from postulations p
inner join listings a on p.idlisting = a.idlisting
where a.idlisting in ('1001972582',
'1001964448',
'1001926936')

The answer should be the amount of unique postulants that subscribe to all the listings that have over 500 postulations.

Please let me know if it's understandable.

Thanks for the help.

Pietro
  • 125
  • 1
  • 3
  • 11

2 Answers2

1

Just putting the first query in the 'in' clause should work. Or are you looking for a cleaner version?

select count(distinct p.idpostulant)
from postulations p
inner join listings a on p.idlisting = a.idlisting
where a.idlisting in (
      select a.idlisting
      from postulations p
      inner join listings a on p.idlisting = a.idlisting
      where a.idate >= '2014-07-01'
      and a.idate < '2014-08-01'
      group by a.idlisting
      having count(p.idpostulant) > 500)
bowlturner
  • 1,968
  • 4
  • 23
  • 35
1

Just use join and subqueries:

select count(distinct p.idpostulant)
from postulations p inner join
     listings a
     on p.idlisting = a.idlisting inner join
     (select a.idlisting, count(p.idpostulant) as Total_postulants
      from postulations p inner join
           listings a
           on p.idlisting = a.idlisting
      where a.idate >= '2014-07-01' and a.idate < '2014-08-01'
      group by a.idlisting
      having total_postulants > 500
     ) filter
     on a.idlisting = filter.idlisting;

EDIT:

You can slightly simplify the above query by removing one of the joins in the outer query:

select count(distinct p.idpostulant)
from postulations p inner join
     (select a.idlisting, count(p.idpostulant) as Total_postulants
      from postulations p inner join
           listings a
           on p.idlisting = a.idlisting
      where a.idate >= '2014-07-01' and a.idate < '2014-08-01'
      group by a.idlisting
      having total_postulants > 500
     ) filter
     on p.idlisting = filter.idlisting;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Your query worked, but it took two minutes to fetch the answer. I'll try the other answer I have left to see which one is more efficient. – Pietro Aug 07 '14 at 20:04
  • @Pietro . . . It is hard to know if that is reasonable without knowing about the size of your current data and the indexing structure. – Gordon Linoff Aug 07 '14 at 20:10
  • One of the tables is big, lisitng is 7GB and postulations 80GB – Pietro Aug 07 '14 at 20:16