我需要编写查询以从表值中找到最大值。
表结构如下,
col col2 col3
1 a1 20150102
2 c1 20150201
3 a1 20150301
4 c1 20150101
我希望结果如下
c1 = 20150201
a1 = 20150301
Select * from table1 where col3 = (select max(col3) from table1);
答案 0 :(得分:2)
使用GROUP BY
和MAX
功能。
SELECT col2, MAX(col3)
FROM table1
GROUP BY col2
输出
col2 MAX(col3)
a1 20150301
c1 20150201
答案 1 :(得分:0)
这样我们也可以使用Row_number
DECLARE @Table1 TABLE
(col int, col2 varchar(2), col3 int)
;
INSERT INTO @Table1
(col, col2, col3)
VALUES
(1, 'a1', 20150102),
(2, 'c1', 20150201),
(3, 'a1', 20150301),
(4, 'c1', 20150101)
;
select T.col2,T.col3 from @Table1 T
INNER JOIN (select RN from (select (ROW_NUMBER()OVER(PARTITION BY col2 ORDER BY col3))RN from @Table1)T GROUP BY T.RN )TT ON T.col = TT.RN
ORDER BY T.col2 DESc