获得职位持有人

时间:2014-08-28 05:00:57

标签: sql sql-server tsql sql-server-2008-r2

我有学生'来自36个地区的结果数据。我试图在 SQL Server 查询的帮助下从每个区域获得前三名的持有者。我通过以下查询得到了成功:

select 
  District, 
  ROLL_NO, 
  ENG, 
  URDU, 
  MATH, 
  SCI, 
  ISL , 
  (cast(Eng as int) + CAST(urdu as int)+ CAST(MATH as int) + CAST(SCI as int) + CAST(ISL as int)) as  TotalScore 
from G5G8
ORDER BY DISTRICT, TotalScore DESC

此查询产生前三名结果,但所有其他学生的输出也是,但我想从每个区只获得前三名的位置(总共36 x 3 = 108条记录) 请建议我应该在此查询中添加更多内容。

我正在使用SQL Server 2008 R2

1 个答案:

答案 0 :(得分:0)

您可能正在寻找类似以下的查询,

SELECT
    t.District,
    t.ROLL_NO,
    t.ENG,
    t.URDU,
    t.MATH,
    t.SCI,
    t.ISL,
    t.TotalScore,
FROM 
(
    SELECT 
        District, 
        ROLL_NO, 
        ENG, 
        URDU, 
        MATH, 
        SCI, 
        ISL , 
        (cast(Eng as int) + CAST(urdu as int)+ CAST(MATH as int) + CAST(SCI as int) + CAST(ISL as int))as TotalScore
        rowid = ROW_NUMBER() OVER (PARTITION BY District ORDER BY TotalScore) 
    FROM 
        G5G8 
    ORDER BY 
        TotalScore DESC
    GROUP BY 
        District
) AS t
WHERE t.rowid <= 3
ORDER BY t.TotalScore
GROUP BY t.District
如果我能知道你的桌子结构,我会更清楚。但是,您可以查看here