简体   繁体   中英

SQL - Selecting all or none in a set of rows

I have a table where multiple entries are grouped by having the same number. Each of these rows also have a result.

Example

id 4 | Group 5 | Result 1
id 5 | Group 5 | Result 1
id 6 | Group 6 | Result 0
id 7 | Group 6 | Result 1

How would I go about selecting the highest number group where all their result is the same number?

In otherwords, say I want to get the highest group where result = 1 ; I would not want group 6 as there is a result is 0, nor would I want any groups older than group 4 as all of group 5 have a result of 1.

There's a couple of different ways to do this. Here's one approach to select the highest group using order by and limit where all results are 1 using max and min :

select grp
from yourtable
group by grp
having max(result) = 1 and min(result) = 1
order by grp desc
limit 1

This is a slightly dierent approach.

SELECT `group` FROM `test` 
GROUP BY `group`
HAVING COUNT(`result`)=SUM(`result`) AND SUM(`result`)>0
ORDER BY `group` DESC LIMIT 1;

Check it on SQL Fiddle

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