开发者

sql - getting the id from a row based on a group by

Table A

  • tableAID
  • tableBID
  • grade

Table B

  • tableBID
  • name
  • description

Table A links to Table b from the tableBID found in both tables.

If I want to find the开发者_如何学Python row in Table A, which has the highest grade, for each row in Table B, I would write my query like this:

select max(grade) from TableA group by tableBID

However, I don't just want the grade, I want the grade plus id of that row.


You could try something like

SELECT  a.*
FROM    TableA a INNER JOIN
        (
            SELECT  tableBID,
                    MAX(grade) MaxGrade
            FROM    TableA
            GROUP BY tableBID
        ) B ON a.tableBID = B.tableBID AND a.grade = B.MaxGrade

Using the Sql Server 2005 ROW_NUMBER function you could also try

SELECT  tableAID,
        tableBID,
        grade
FROM    (
            SELECT  *,
                    ROW_NUMBER() OVER (PARTITION BY tableBID ORDER BY grade DESC) RowNum
            FROM    @TableA
        ) A
WHERE   a.RowNum = 1


Assuming you will only have one Max() (HUGE ASSUMPTION) you can do min(tableaid) where grade = (select max(grade) etc....)

or if you want all matching ids

SELECT TableAID, Grade
FROM TableA INNER JOIN (SELECT  tableBID,
     MAX(grade) Grade
     FROM    TableA
     GROUP BY tableBID) MaxGrade 
ON TableA.Grade = MaxGrade.Grade 


Just use a little self-referencing NOT EXISTS clause:

DECLARE @tableA TABLE (tableAID int IDENTITY(1,1), tableBID int, grade int)

INSERT INTO @tableA(tableBID, grade) VALUES(10, 1)
INSERT INTO @tableA(tableBID, grade) VALUES(10, 3)
INSERT INTO @tableA(tableBID, grade) VALUES(20, 4)
INSERT INTO @tableA(tableBID, grade) VALUES(20, 8)
INSERT INTO @tableA(tableBID, grade) VALUES(30, 10)
INSERT INTO @tableA(tableBID, grade) VALUES(30, 6)

SELECT tableAID, grade
FROM @tableA ta
WHERE NOT EXISTS (SELECT 1 FROM @tableA WHERE tableBID = ta.tableBID AND grade > ta.grade)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜