[英]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
; 换句话说,说我想得到
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. 我不想使用第6组,因为结果为0,也不需要任何比第4组更旧的组,因为第5组的所有结果都为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
: 这是一种使用
order by
和limit
来选择最高group
方法,其中使用max
和min
limit
所有结果均为1
:
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 在SQL Fiddle上检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.