0

我有一张类似的桌子

id-value-RowInid
1-xy-1
1-xx-2
1-xz-3
2-xx-1
2-xr-2
3-xq-1
4-xa-1
4-xc-2
...

我需要一个具有相似输出的表的函数来获得分离 id 组中的最大 RowInid

1-xz-3
2-xr-2
3-xq-1
4-xc-2
...
4

3 回答 3

4

你只需要MAX(RowInid)使用GROUP BY Id, value

SELECT ID, VALUE, MAX(RowInid) FROM myTable GROUP BY ID, VALUE

编辑:
当您更新您的问题时,您可以value使用这样的子查询获取字段:

SELECT ID, VALUE, RowInid
FROM myTable t1 WHERE RowInid = 
(
    SELECT MAX(RowInid) FROM myTable WHERE id = t1.id GROUP BY id
)
ORDER BY id ASC;

您也可以使用以下方法实现此INNER JOIN目的:

SELECT t2.ID, VALUE, t2.RowInid FROM myTable t1
INNER JOIN 
(
    SELECT ID, MAX(RowInid) AS RowIniD FROM myTable GROUP BY ID
) AS t2
ON t1.ID = t2.ID AND t1.RowInid = t2.RowInid
ORDER BY t1.ID ASC;

看到这个 SQLFiddle

查看有关SQL Server 的GROUP BY更多信息。MAX

于 2012-09-08T14:45:05.247 回答
2

根本不需要 group by 或 max

select id, value, rowinid from
( select *, row_number() over (partition by id, order by rowinid desc) rn from yourtable ) v
where rn = 1
于 2012-09-09T06:19:17.620 回答
0

尝试,

使用 Sub Query 获取 Id、Value 和 Max RowInid,

  SELECT m1.[Id],m1.Value, m1.RowInid
  FROM [Practice].[dbo].[myTable] m1 WHERE RowInid = (SELECT MAX(m2.RowInid) FROM [Practice].[dbo].[myTable] m2 WHERE M1.Id = m2.Id GROUP BY Id)

以上查询返回结果如:4-xx-2 3-xx-1 2-xx-2 1-xx-3

为了提升这种用途,

SELECT  m1.[id],m1.Value, m1.RowInid
FROM [Practice].[dbo].[myTable] m1 WHERE m1.RowInid = (SELECT MAX(m2.RowInid) FROM [Practice].[dbo].[myTable] m2 WHERE M2.id = m1.id GROUP BY id)  ORDER BY m1.id ASC
于 2012-09-08T14:59:10.890 回答