我想要一条 SQL 语句来获取具有最小值的行。
考虑这张表:
id game point
1 x 5
1 z 4
2 y 6
3 x 2
3 y 5
3 z 8
如何选择point
列中具有最小值的 id,按游戏分组?如下所示:
id game point
1 z 4
2 y 5
3 x 2
我想要一条 SQL 语句来获取具有最小值的行。
考虑这张表:
id game point
1 x 5
1 z 4
2 y 6
3 x 2
3 y 5
3 z 8
如何选择point
列中具有最小值的 id,按游戏分组?如下所示:
id game point
1 z 4
2 y 5
3 x 2
利用:
SELECT tbl.*
FROM TableName tbl
INNER JOIN
(
SELECT Id, MIN(Point) MinPoint
FROM TableName
GROUP BY Id
) tbl1
ON tbl1.id = tbl.id
WHERE tbl1.MinPoint = tbl.Point
这是做同样事情的另一种方式,它可以让你做一些有趣的事情,比如选择前 5 名获胜的游戏等。
SELECT *
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Point) as RowNum, *
FROM Table
) X
WHERE RowNum = 1
您现在可以正确获取被识别为得分最低的实际行,并且您可以修改排序函数以使用多个标准,例如“显示得分最低的最早游戏”等。
这将起作用
select * from table
where (id,point) IN (select id,min(point) from table group by id);
由于这sql
仅被标记,因此以下使用 ANSI SQL 和窗口函数:
select id, game, point
from (
select id, game, point,
row_number() over (partition by game order by point) as rn
from games
) t
where rn = 1;
肯克拉克的回答对我来说不起作用。它也可能不适用于您的。如果没有,试试这个:
SELECT *
from table T
INNER JOIN
(
select id, MIN(point) MinPoint
from table T
group by AccountId
) NewT on T.id = NewT.id and T.point = NewT.MinPoint
ORDER BY game desc
SELECT DISTINCT
FIRST_VALUE(ID) OVER (Partition by Game ORDER BY Point) AS ID,
Game,
FIRST_VALUE(Point) OVER (Partition by Game ORDER BY Point) AS Point
FROM #T
这是可移植的——至少在 ORACLE 和 PostgreSQL 之间:
select t.* from table t
where not exists(select 1 from table ti where ti.attr > t.attr);
SELECT * from room
INNER JOIN
(
select DISTINCT hotelNo, MIN(price) MinPrice
from room
Group by hotelNo
) NewT
on room.hotelNo = NewT.hotelNo and room.price = NewT.MinPrice;
这种替代方法使用 SQL Server 的OUTER APPLY
子句。这样一来,
该OUTER APPLY
子句可以想象为LEFT JOIN
,但其优点是您可以将主查询的值用作子查询中的参数(此处为:游戏)。
SELECT colMinPointID
FROM (
SELECT game
FROM table
GROUP BY game
) As rstOuter
OUTER APPLY (
SELECT TOP 1 id As colMinPointID
FROM table As rstInner
WHERE rstInner.game = rstOuter.game
ORDER BY points
) AS rstMinPoints
尝试:
select id, game, min(point) from t
group by id