sql - 找到最大值

时间:2011-12-10 19:51:28

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

我有一个包含3列的表:代码,年份,百分比。

我需要在2009年返回具有最低(最小)百分比的代码。在此之后,我还想要代码的名称,在我创建的其他表格中存在。

我只想使用CREATE VIEW,但我不想这样做。

4 个答案:

答案 0 :(得分:5)

Select table.code, table.year, table.percentage, othertable.name
from table
inner join othertable  on table.FKId = othertable.PKid
where year = 2009 
  and percentage = 
  (select min(percentage) 
   from table 
   where year = 2009)

更新以包含othertable ......因为我们没有名字。

已更新  现在我们有了表名...现在第3次更新,我知道年份是字符串。

Select E.Code, C.Name 
From dbo.Exam E
inner join dbo.Course C
  ON E.Code = C.Code  
Where E.Year = '2009' and --<-- PROBLEM LIKELY HERE year was string not int.
 E.Fail = (select MIN(E2.Fail) 
                  from dbo.Exam E2 where E2.Year = '2009') --<--Don't forget here too.

来自评论:示例数据:

 INSERT INTO Exam VALUES(333,'2009',40) 
 INSERT INTO Exam VALUES(333,'2009',20) 
 INSERT INTO Exam VALUES(555,'2009',19) 
 INSERT INTO Exam VALUES(444,'2009',19) 
 INSERT INTO Exam VALUES(777,'2009',23) 
 INSERT INTO Exam VALUES(333,'2009',0) 
 INSERT INTO Course VALUES(111,'Name1',5) 
 INSERT INTO Course VALUES(333,'Name2',5) 
 INSERT INTO Course VALUES(444,'Name3',6) 
 INSERT INTO Course VALUES(555,'Name4',3) 
 INSERT INTO Course VALUES(777,'Name5',3) 
 INSERT INTO Course VALUES(999,'Name6',6) 

应该是假设的结果 Name2,5

答案 1 :(得分:0)

您可以使用group by查找一年中最低的百分比,然后重新加入主表以查找相应的其他列:

select  *
from    CodeYearPercTbl cyp
join    CodeTbl c
on      c.Code = cyp.Code
join    (
        select  Year
        ,       min(Percentage) as MinPerc
        from    CodeYearPercTbl
        group by
                Year
        ) as filter
on      filter.Year = cyp.Year
        and filter.MinPerc = cyp.Percentage
where   cyp.Year = 2009

答案 2 :(得分:0)

表-1:代码,年份,百分比 表-2:代码,CodeName

select T1.Code,T2.CodeName,T1.Percentage from
(
     select TOP 1 Code,Percentage 
     from Table-1 
     where Year = '2009' 
     order by Percentage asc
) T1  inner join Table-2 T2 on T1.Code = T2.Code

答案 3 :(得分:0)

试试这个:

select a.Code, c.Name 
from  YourTable a inner join AnotherTable c on a.Code = c.Code 
where a.Percentage = (select MIN(Percentage) 
                      from YourTable  b where b.Year = '2009'
                     )