SQLSERVER分组依据(基于其他列的聚合列)

时间:2014-06-27 18:57:32

标签: sql sql-server group-by

我有一张表有3列A,B,C

我想做这样的查询:

select A, Max(B), ( C in the row having max B ) from Table group by A.

有没有办法进行这样的查询?

测试数据:

A    B    C
2    5    3
2    6    1
4    5    1
4    7    9
6    5    0

预期结果将是:

2    6    1
4    7    9
6    5    0

2 个答案:

答案 0 :(得分:2)

;WITH CTE AS
(
    SELECT  A,
            B,
            C,
            RN = ROW_NUMBER() OVER(PARTITION BY A ORDER BY B DESC)
    FROM YourTable
)
SELECT A, B, C
FROM CTE
WHERE RN = 1

答案 1 :(得分:1)

试试这个

select t.*
from   table t
join   (Select A,max(b) B from table group by A) c
on  c.a=t.a
and c.b=a.b