[英]Return unique rows based on certain criteria
I need a query that will return distinct rows, but will not return any rows that have duplicate fruits where one of the rows is 'Approved'. 我需要一个查询,该查询将返回不同的行,但不会返回其中有一个行为“已批准”的具有重复结果的任何行。 Note: there will always be at most two fruits of the same name.
注意:最多将有两个同名水果。
For example, the ideal result would be: 例如,理想的结果将是:
What I have so far is simply: 到目前为止,我只是简单地:
SELECT DISTINCT * FROM Food;
But this obviously still returns one of the rows that has the fruit 'Apple' 但这显然仍返回结果为“苹果”的行之一
You can make use of some conditional aggregation for the desired result set like 您可以为所需的结果集使用一些条件聚合,例如
select fruit, min(status)
from demo
group by fruit
having sum(status = 'Approved') = 0
and sum(status = 'Bought') > 0
or just use select fruit, 'Bought' as status
或仅使用
select fruit, 'Bought' as status
SELECT DISTINCT * FROM Food WHERE Fruit NOT IN (SELECT (UNIQUE Fruit) FROM Food WHERE Status = 'Approved');
试试这个查询。
I think you could solve this problem a different way perhaps? 我认为您也许可以通过其他方式解决此问题? To get that same result you could add a
WHERE
clause, for instance: 为了获得相同的结果,您可以添加一个
WHERE
子句,例如:
SELECT DISTINCT * FROM Food WHERE Status = 'Bought';
You could also alter the data model so that a fruit's status is updated rather than adding another record for the same fruit (if that suits the application's purposes). 您还可以更改数据模型,以便更新水果的状态,而不是为同一水果添加另一个记录(如果适合应用程序的目的)。
If you want to maintain the schema and get the same, I believe you can do: SELECT DISTINCT on (Fruit) Fruit, Status FROM Food ORDER BY Fruit, Status ASC;
如果您想维护模式并获得相同的结果,我相信您可以这样做:
SELECT DISTINCT on (Fruit) Fruit, Status FROM Food ORDER BY Fruit, Status ASC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.