从表格值

时间:2015-10-28 11:03:16

标签: mysql sql

我需要编写查询以从表值中找到最大值。

表结构如下,

col  col2  col3
1    a1    20150102
2    c1    20150201
3    a1    20150301
4    c1    20150101

我希望结果如下

输出:table1

c1 = 20150201
a1 = 20150301

我的查询:

Select * from table1 where col3 = (select max(col3) from table1);

2 个答案:

答案 0 :(得分:2)

使用GROUP BYMAX功能。

SELECT col2, MAX(col3)
FROM table1
GROUP BY col2

输出

col2    MAX(col3)
a1      20150301
c1      20150201

SQL小提琴:http://sqlfiddle.com/#!9/73026/1/0

答案 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