我正在尝试使用如下信息表:
+----+---+---+
| ID | X | Y |
+----+---+---+
| A | 1 | 3 |
| A | 1 | 1 |
| A | 1 | 2 |
| A | 1 | 7 |
| B | 2 | 2 |
| B | 3 | 3 |
| B | 1 | 9 |
| B | 2 | 4 |
| B | 2 | 1 |
| C | 1 | 1 |
+----+---+---+
我希望能够在两列中选择最小值,按第一列分组 - “X”列比Y列更重要。例如,查询应返回如下内容:
+----+---+---+
| ID | X | Y |
+----+---+---+
| A | 1 | 1 |
| B | 1 | 9 |
| C | 1 | 1 |
+----+---+---+
有什么想法吗?到目前为止,我已经完成了几十个帖子和实验,但没有运气。
谢谢, 詹姆斯
答案 0 :(得分:3)
您似乎希望行具有最小x值。并且,如果x上有重复项,那么请选择具有最小y的那个。
为此,请使用row_number()
:
select id, x, y
from (select t.*,
row_number() over (partition by id order by x, y) as seqnum
from t
) t
where seqnum = 1
如果您的数据库不支持窗口函数,您仍然可以在SQL中表达:
select t.id, t.x, min(t.y)
from t join
(select id, MIN(x) as minx
from t
group by id
) tmin
on t.id = tmin.id and t.x = tmin.minx
group by t.id, t.x
答案 1 :(得分:2)
如果您的RDBMS支持窗口功能,
SELECT ID, X, Y
FROM
(
SELECT ID, X, Y,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY X, Y) rn
FROM tableName
) d
WHERE rn = 1