简体   繁体   English

SQL 在 ORACLE 中使用 GROUP BY 和 HAVING COUNT(condition) 查询

[英]SQL query with GROUP BY and HAVING COUNT(condition) in ORACLE

I have three tables: temp, product and feed.我有三个表:温度、产品和饲料。 I'll show on example:我将举例说明:

select ri.id from temp ri
inner join product i on ri.id = to_char(i.val)
inner join feed f on f.product_id = i.product_id
where i.status = 'Finished'
and f.type = 'Type'
group by f.feed_id, ri.id
having COUNT(f.status = 'SUCCESS') < 1;

so I tried to get all ids from temp that have f.type = 'Type' .所以我试图从temp中获取所有具有f.type = 'Type' ID。 Problem is that for one feed.feed_id can be many rows because I could retrigger it 5 times and let's say 4 times it crashed but at 5th attempt it was SUCCESS , so for one feed.feed_id I would have 5 rows and only one would be with f.status = SUCCESS .问题是对于一个feed.feed_id可以是多行,因为我可以重新触发它 5 次,假设它崩溃了 4 次,但在第 5 次尝试时它是SUCCESS ,所以对于一个feed.feed_id我将有 5 行,只有一个是与f.status = SUCCESS

Error which I receive for this query is ORA-00907: missing right parenthesis which makes me totally confused.我收到的此查询的错误是ORA-00907: missing right parenthesis ,这让我完全困惑。

feed table : feed_id , status , type I am interested in all feed_id which don't have even one status='SUCCESS' for type='TYPE' feed tablefeed_idstatustype我对所有feed_id感兴趣,它们甚至没有一个status='SUCCESS' for type='TYPE'

You can't COUNT a boolean expression in Oracle, you can use a CASE expression instead eg您不能在COUNT中计算 boolean 表达式,您可以使用CASE表达式,例如

HAVING COUNT(CASE WHEN f.status = 'SUCCESS' THEN 1 END) < 1

This expression returns NULL when the condition is false, so it will only count the rows for which the condition is true (since COUNT of an expression ignores NULL values).此表达式在条件为假时返回NULL ,因此它只会计算条件为真的行(因为表达式的COUNT忽略NULL值)。

Note also (as @GordonLinoff points out in the comments) that since COUNT cannot return a negative number, it is cleaner (and would be more efficient) to simply compare the result for equality with 0, rather than being less than 1:另请注意(正如@GordonLinoff 在评论中指出的那样),由于COUNT不能返回负数,因此简单地将结果与 0 进行比较而不是小于 1 更简洁(并且效率更高):

HAVING COUNT(CASE WHEN f.status = 'SUCCESS' THEN 1 END) = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM