我还有一个关于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
的所有行,第二个结果是由art
、ean
、obs
分组的具有obs
的所有行等于vke
的0
和min
值。
阅读有关union
和group 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
)