简体   繁体   English

根据特定条件返回唯一行

[英]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

Demo 演示版

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;

Source 资源

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

相关问题 SQL查询返回行数,直到满足某些条件 - SQL Query to return count of rows until certain criteria is met 根据MySQL中的最小ID返回唯一的行 - Return unique rows based on minimum id in mysql 根据某些条件运行SQL查询并仅删除x行? - Run a SQL query based on certain criteria and delete only x rows? 根据某些条件返回行,如果没有行符合条件,则返回mariadb sql中的所有行 - returning rows based on some criteria and if no row match the criteria then return all rows in mariadb sql 选择行 - 作为条件的唯一字段 - Selecting rows - unique field as criteria mySQL 连接表,但根据来自另一列的匹配条件排除具有特定 ID/值的所有行(条件仅包含在某些行中) - mySQL Join Tables but exclude ALL rows with a certain ID/value based on matching criteria from another column (criteria contained in only some rows) MySQL查询:当另一列中的值符合特定条件时,返回一列中具有特定值的所有行 - MySQL Query: Return all rows with a certain value in one column when value in another column matches specific criteria 根据两个条件条件为每个唯一 ID 返回不同值的多个 COUNT 字段 - Return multiple COUNT fields for distinct values per a unique ID based on two criteria conditions 基于列的唯一行 - Unique Rows based on Column 根据多个条件删除行 - Delete rows based on multiple criteria
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM