[英]How to select multiple distinct data from a table?
Following is my table and I want to select the records having unique id1 and minimum difference, I have already tried this: 以下是我的表,我想选择具有唯一id1和最小差异的记录,我已经尝试过了:
select * from table group by (id1) having min(difference)
but this returns only one record 但这仅返回一条记录
| ID1 | ID2 | DIFFERENCE |
|-----|-----|------------|
| 1 | 1 | 1 |
| 1 | 2 | 3 |
| 1 | 3 | 4 |
| 2 | 1 | 3 |
| 2 | 3 | 4 |
Now I want to select the records having minimum difference ie I want first row and 4th row from table because both having minimum difference and different id1. 现在,我想选择具有最小差异的记录,即我想要表中的第一行和第四行,因为它们都具有最小差异且具有不同的id1。
Try using sub-query like this: 尝试使用子查询,如下所示:
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;
If you want to select only ID1
and Difference
columns then you can do this even without using sub-query: 如果您只想选择ID1
和Difference
列,那么即使不使用子查询也可以这样做:
SELECT ID1, MIN(difference) AS MinDif
FROM Table1
GROUP BY ID1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.