使用distinct和/或group by来过滤选择

时间:2012-02-08 09:26:41

标签: mysql group-by distinct

我还有一个关于不同和/或分组的问题。我的表格如下:

|   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    |

2 个答案:

答案 0 :(得分:1)

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

我{d} union两个结果第一个是obs水族1的所有行,第二个行按art分组,eanobs obs等于0min值为vke

详细了解uniongroup by

答案 1 :(得分:1)

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
)