简体   繁体   中英

Group by non aggregate condition

Is it possible to have non-aggregate condition on groups? For example we have:

Table1(firstName, lastName, gender)

And we group by firstName and then by lastName , but we want only the groups having at least 5 males in it. Or another example is the groups without any male or other conditions like that. Actually I solved it by using case when, but I'm looking to see if there is straight solution for it. Another Form of this problem is when we want only the groups which contains at least one person older than 18, or any question like that.

I don't know if this is anything like your 'solution using case', but I think this is the most straightforward way to do it.

Basically, instead of just counting, you can sum the number of rows that match a condition, so the pattern is always: SUM(CASE WHEN <condition> THEN 1 [ELSE 0] END . In the HAVING clause, you can filter by such aggregations.

Since count doesn't count null s, you could also write it as COUNT(CASE WHEN <condition> THEN 1 [ELSE null] END) . This method is arguably more clear than the SUM way, but I'm more used to that one.

SELECT
  FirstName, LastName
FROM
  Table1
GROUP BY
  FirstName, LastName
HAVING 
  SUM(CASE WHEN Gender = 'M' THEN 1 ELSE 0 END) >= 5

The above condition is for 'at least 5 males'.

To write 'exacty 3 woman and at least one person older than 18', you could do it like this:

HAVING 
  SUM(CASE WHEN Gender = 'F' THEN 1 ELSE 0 END) = 3
  SUM(CASE WHEN Age > 18 THEN 1 ELSE 0 END) >= 1

Those conditions work separately, so in the condition above, the 18 year old person could be one of the three women or a guy. But you can also combine the conditions inside the case. For instance: 'at least 5 men who are 18 or older':

HAVING 
  SUM(CASE WHEN Gender = 'M' AND Age >= 18 THEN 1 ELSE 0 END) >= 5

I hope these examples will help you find the condition you need.

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