以下是我的表格,我想选择具有唯一ID1和最小差异的记录,我已经尝试过这个:
select * from table group by (id1) having min(difference)
但这只返回一条记录
| ID1 | ID2 | DIFFERENCE |
|-----|-----|------------|
| 1 | 1 | 1 |
| 1 | 2 | 3 |
| 1 | 3 | 4 |
| 2 | 1 | 3 |
| 2 | 3 | 4 |
现在我想选择具有最小差异的记录,即我想从表中获得第一行和第四行,因为它们具有最小差异和不同的id1。
答案 0 :(得分:0)
尝试使用这样的子查询:
SELECT DISTINCT t1.* FROM Table1 t1
JOIN
(
SELECT ID1, MIN(difference) AS MinDif
FROM Table1
GROUP BY ID1
) t2
ON t1.ID1 = t2.ID1
AND t1.difference = t2.MinDif;
如果您只想选择ID1
和Difference
列,那么即使不使用子查询也可以执行此操作:
SELECT ID1, MIN(difference) AS MinDif
FROM Table1
GROUP BY ID1