获取内部联接组查询中每个唯一组的第一行

时间:2010-11-09 02:57:22

标签: sql sql-server tsql greatest-n-per-group

表1

id    name   class
1     ab     A
2     cd     A
3     ef     B    
4     ab     B
5     cd     B

表2

name   test   marks
ab     1      90
ab     2      70
cd     2      80
cd     3      85
ef     3      85
ef     4      60

嗨,我上面有2个表,我的问题是从表2中获得每个人最高分的最有效/最好或最简单的方法是什么,并加入表1以便返回:

id   name   class    [highest marks]
1    ab     A        90
2    cd     A        85
3    ef     B        85

2 个答案:

答案 0 :(得分:2)

假设SQL Server 2005+,使用分析/排名/窗口功能:

WITH example AS (
  SELECT a.id,
         a.name,
         a.class,
         b.marks,
         ROW_NUMBER() OVER(PARTITION BY a.id
                               ORDER BY b.marks DESC) AS rank
    FROM TABLE_1 a
    JOIN TABLE_2 b ON b.name = a.name)
SELECT e.id,
       e.name,
       e.class,
       e.marks
  FROM example e
 WHERE e.rank = 1

使用聚合:

SELECT a.id,
       a.name,
       a.class,
       b.marks      
  FROM TABLE_1 a
  JOIN (SELECT t.name,
               MAX(t.mark) AS max_mark
          FROM TABLE_2
      GROUP BY t.name) b ON b.name = a.name

答案 1 :(得分:0)

如果您不想使用CTE(公用表格表达式)

,则另一种选择
SELECT table1.id, table1.name, table1.class, MAX(table2.marks) AS [highest marks]
FROM table1 INNER JOIN
table2 ON table1.name = table2.name
GROUP BY table1.id, table1.name, table1.class