表A
表B
表A从两个表中的tableBID链接到表b。
如果我想找到表A中具有最高等级的行,对于表B中的每一行,我会像这样编写我的查询:
select max(grade) from TableA group by tableBID
但是,我不仅仅想要成绩,我想要该等级加上该行的ID。
答案 0 :(得分:4)
您可以尝试类似
的内容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
使用Sql Server 2005 ROW_NUMBER功能,您也可以尝试
SELECT tableAID,
tableBID,
grade
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY tableBID ORDER BY grade DESC) RowNum
FROM @TableA
) A
WHERE a.RowNum = 1
答案 1 :(得分:0)
假设你只有一个Max()(巨大的假设)你可以做min(tableaid),其中grade =(选择max(grade)等......)
或者如果您想要所有匹配的ID
SELECT TableAID, Grade
FROM TableA INNER JOIN (SELECT tableBID,
MAX(grade) Grade
FROM TableA
GROUP BY tableBID) MaxGrade
ON TableA.Grade = MaxGrade.Grade
答案 2 :(得分:0)
只需使用一点自我引用NOT EXISTS子句:
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)