[英]MySQL return prioritizes value else return other value
I have a table (This is a mock-table), 我有一张桌子(这是一个模拟桌子),
+------------+------+--------+
| Name | Code | Active |
+------------+------+--------+
| Sales | 55 | 1 |
| Sales | 55 | 0 |
| IT | 22 | 1 |
| Production | 33 | 1 |
| Production | 33 | 0 |
| Marketing | 77 | 0 |
| Marketing | 77 | 0 |
+------------+------+--------+
And I want to return a list of distinct names and codes. 我想返回一个不同名称和代码的列表。 However, I want to determine if the department is active or not. 但是,我想确定部门是否处于活动状态。 so if Sales has a 1
in active and a 0
in active they are active, but is they had only zeros then they are not. 因此,如果Sales的活动状态为1
活动状态为0
,则它们处于活动状态,但是如果它们只有零,则它们不是活动状态。
I've tried a variety of methods and read through a few dozen SO post, but am not gaining any progress. 我尝试了多种方法并通读了几十篇SO文章,但是没有取得任何进展。
The output I am trying to achieve is: 我想要实现的输出是:
+------------+------+--------+
| Name | Code | Active |
+------------+------+--------+
| Sales | 55 | 1 |
| IT | 22 | 1 |
| Production | 33 | 1 |
| Marketing | 77 | 0 |
+------------+------+--------+
How can I prioritize the Active
column to a value of 1
, but still return an entry if all entries with the same code have a value of 0
(such as marketing)? 如何将“ Active
列的优先级设置为1
,但是如果所有具有相同代码的条目的值都为0
(例如市场营销),仍然返回一个条目?
GROUP BY
name and code and get the maximum value of Active. GROUP BY
名称和代码并获得Active的最大值。 (Assuming 0 and 1 are the possible values for Active column) (假设0和1是“活动”列的可能值)
SELECT Name,Code,MAX(Active) active
FROM tablename
GROUP BY Name,Code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.