使用distinct和/或group by进行筛选选择



我还有一个关于distinct和/或group-by的问题。我的表如下:

|   art   |   ean             |   obs   |   vke   |
---------------------------------------------------
|  type    |  1234567890123   |    1    |   100   |
|  type    |  1234567890123   |    0    |   50    |
|  type    |  1234567890123   |    0    |   60    |
|  type    |  1234567890123   |    0    |   70    |

我需要查询始终选择obs=1的行,并且只选择obs=0的其他行中最便宜的一行。根本不应列出所有其他相等的EAN。这可能吗?

所以结果应该是:

|  type    |  1234567890123   |    1    |   100   |
|  type    |  1234567890123   |    0    |   50    |
select art, ean, obs, vke 
from table_name
where obs = 1
union all
select art, ean, obs, min(vke) as vke
from table_name
where obs = 0
group by art, ean, obs

我将union的两个结果——第一个结果是具有obs aquals 1的所有行,第二个结果是由arteanobs分组的具有obs的所有行等于vke0min值。

阅读有关uniongroup by的更多信息。

SELECT art, ean, obs, vke
FROM table_name
WHERE obs = 1
UNION ALL
(
    SELECT art, ean, obs, vke
    FROM table_name
    WHERE obs = 0
    ORDER BY vke
    LIMIT 1
)

最新更新