简体   繁体   中英

How to make a query with the operator MIN() and something filtered inside in JPQL?

I have a class Sponsor who has a Collection<Campaign> . And each Campaign has just one Sponsor .

For example, if I have it:

SELECT MIN(s.campaigns.size) FROM Sponsor s;

It returns the campaigns.size of the Sponsor who has the minimum campaigns.

But if I want to COUNT the campaigns 'c' whose c.attribute=null per Sponsor, and then return the minimum of it?

A visual example of what I want to get could be:

select min(select count(c) from Campaign c where c.sponsor.id=s.id and c.finishMoment is null) from Sponsor s;

The thing is that it's not possible to include a SELECT into the function MIN.

Hard to say what your looking for. Here's something along those lines.

** Sorry, not a jpql guy, but apparently you can take the first result, so you could do the select and order it by the count and just take the first result

Sorry, your going to have to work out the join, but you get the idea.

SELECT Campaign.id,COUNT(Campaign.id)  
FROM Campaign
JOIN Sponsor on (Sponsor.id = Campaign.id)
WHERE finishMoment is null   
GROUP BY Campaign.id
ORDER BY COUNT(Campaign.id)

**This is SQL

SELECT MIN(sponsorCount)   
FROM (SELECT Campaign.id,COUNT(*) sponsorCount   
      FROM Campaign
      JOIN Sponsor on (Sponsor.id = Campaign.id)
      WHERE finishMoment is null   
      GROUP BY Campaign.id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM