假设我有一个名为process_states
的表:
+--------+--------+
|Process | State |
-------------------
| A | 0 |
| A | 0 |
| B | 0 |
| B | -1 |
| C | -99 |
-------------------
Note: State can have many more negative and positive state values
我想找到所有行状态为0的进程。在上面的例子中,我想得到A。
我试图使用group by
来做,有没有办法做这样的事情:
select process from process_states
group by process
having <all state for that process is 0>
可以使用group by
吗?
答案 0 :(得分:3)
您可以使用group by
子句并使用having
子句过滤进程:
SELECT process
FROM process_states
GROUP BY process
HAVING COUNT(CASE state WHEN -1 THEN 1 END) = 0
编辑:
鉴于对其他答案的澄清评论,如果要求仅查找仅具有0
个状态的进程,则可以计算总行数和具有0
状态的行数并比较它们:
SELECT process
FROM process_states
GROUP BY process
HAVING COUNT(CASE state WHEN 0 THEN 1 END) = COUNT(*)
答案 1 :(得分:2)
您可以group by
处理列并检查状态列的最大值和最小值是否为0
。
select process
from process_states
group by process
having max(state) = min(state) and min(state) = 0
答案 2 :(得分:1)
您可以使用having
子句来完成此操作。如果给定进程的行数等于具有零的行数,则表示该进程只有零行。
select process
from process_states
group by process
having count(*) = count(case when state = 0 then 'X' end)
答案 3 :(得分:1)
我很想将min
用于此:
select process
from process_status
group by process
having min(status) > -1;
这确实假设没有其他负面状态。
答案 4 :(得分:1)
试试这个
select process
from process_status
group by process
having sum(abs(status)) = 0