如何找出a字段相同情况下b字段最大的那个记录
例如表t
a b
1 5
1 2
2 8
2 3
4 9
4 8
4 5
要找到以下结果
1 5
2 8
4 9
还有就是t是join之后的一个临时表
[解决办法]
select a,max(b) b from t group by a
WITH a1 (a,b,c) AS
(
SELECT 1, 5,'a' UNION ALL
SELECT 1, 2,'g' UNION ALL
SELECT 2, 8,'d' UNION ALL
SELECT 2, 3,'g' UNION ALL
SELECT 4, 9,'b' UNION ALL
SELECT 4, 8,'d' UNION ALL
SELECT 4, 5,'c'
)
,a2 AS
(
SELECT a,MAX(b) b FROM a1 GROUP BY a
)
SELECT a1.a,a1.c
FROM a1
INNER JOIN a2 ON a1.a=a2.a AND a1.b=a2.b
WITH a1 (a,b,c) AS
(
SELECT 1, 5,'a' UNION ALL
SELECT 1, 2,'g' UNION ALL
SELECT 2, 8,'d' UNION ALL
SELECT 2, 3,'g' UNION ALL
SELECT 4, 9,'b' UNION ALL
SELECT 4, 8,'d' UNION ALL
SELECT 4, 5,'c'
)
,a2 AS
(
SELECT a,c,ROW_NUMBER() OVER (PARTITION BY a ORDER BY b desc) re
FROM a1
)
SELECT a,c FROM a2 WHERE re=1
DECLARE @t table (a int,b int,c varchar(10))
INSERT INTO @t(a,b,c)
VALUES(1, 5, 'a'),
(1, 2, 'g'),
(2, 8, 'd'),
(2, 3, 'g'),
(4, 9, 'b'),
(4 ,8, 'd'),
(4, 5, 'c');
WITH cte AS
(
SELECT a,b,c,ROW_NUMBER() OVER(PARTITION BY a ORDER BY b desc) AS rownum
FROM @t
)
SELECT * FROM cte WHERE rownum=1