选择主键,其中组中的最大值包含SQL Server

时间:2015-07-24 07:26:29

标签: sql-server

如何在grouping by子句中选择主键,它将从另一个不在group by子句中的表中返回最大值?例如:

表A:

ID table_b_id Value
1  1          100
2  1          200
3  1          150
4  2          300
5  2          200
6  2          100
7  3          100
8  3          200

表B

ID Name
1  A
2  B
3  C

结果预期

B.ID B.Name A.ID
1    A       2   
2    B       4   
3    C       8

我尝试过这样的问题:

select b.id, max(b.name), max(a.id) as kd_rec
from table_a a join table_b
on a.table_b_id = b.id
group by b.id

我不知道如何通过b从表格中获取最大值。

1 个答案:

答案 0 :(得分:1)

如果您不希望来自Name的{​​{1}},那么

<强>查询

tableB

Fiddle demo

如果您希望结果集中也;with cte as ( select rn=row_number() over ( partition by table_b_id order by [Value] desc ),* from tableA ) select table_b_id as [B.ID], ID as [A.ID] from cte where rn=1; ,那么

<强>查询

Name

Fiddle demo

相关问题