9

我想在最高分上加分。我的桌子是

在此处输入图像描述

我想给学生的最高 3 分打分。第 1 高分 5 分,第 2 高分 3 分,第 3 高分 1 分

我正在使用此代码来选择最高分,

select t1.ID, t1.Name, t1.Section, t1.Marks from myTable t1 join 
(select Section, substring_index(group_concat
 (distinct Marks order by Marks desc), ',', 3) as Marks3  
 from myTable group by Section ) tsum  on t1.Section = tsum.Section 
  and find_in_set(t1.Marks, tsum.Marks3) > 0 ORDER BY Section, Marks DESC, ID Desc

我想为第 1 高分加 5 分,为第 2 高分加 3 分,为第 3 高分加 1 分。学生可能会出现重复分数。

请参考http://www.sqlfiddle.com/#!2/dca0c/1

所以我的最终输出

在此处输入图像描述

请帮我..

4

2 回答 2

3

更新你可以这样做

SELECT id, name, section, marks,
       CASE rank WHEN 1 THEN 5
                 WHEN 2 THEN 3
                 WHEN 3 THEN 1
                 ELSE 0
       END points
  FROM
(
  SELECT s.*, @n := IF(@s = section, IF(@m = marks, @n, @n + 1), 1) rank, @m := marks, @s := section
    FROM students s, (SELECT @n := 0) i
   ORDER BY section, marks DESC
) q
HAVING points > 0

输出:

| 身份证 | 姓名 | 部分 | 标记 | 积分 |
--------------------------------------
| 1 | S1 | 1 级 | 55 | 5 |
| 7 | S7 | 1 级 | 32 | 3 |
| 3 | S3 | 1 级 | 25 | 1 |
| 10 | S10 | 二级 | 78 | 5 |
| 14 | S14 | 二级 | 78 | 5 |
| 6 | S6 | 二级 | 66 | 3 |
| 2 | S2 | 二级 | 33 | 1 |
| 13 | S13 | 二级 | 33 | 1 |
| 4 | S4 | 三级 | 65 | 5 |
| 11 | S11 | 三级 | 65 | 5 |
| 5 | S5 | 三级 | 43 | 3 |
| 12 | S12 | 三级 | 43 | 3 |
| 15 | S15 | 三级 | 25 | 1 |

这是SQLFiddle演示

于 2013-08-02T06:53:52.653 回答
1
select t1.ID, t1.Name, t1.Section, t1.Marks, 
case ((SELECT COUNT(distinct MARKS) FROM students t2 WHERE t2.marks > t1.marks
and t1.Section = t2.Section) +1) when 1 then 5 when 2 then 3 else 1 end as Points
from students t1 join
     (select Section, substring_index(group_concat(distinct Marks order by Marks desc), ',', 3) as Marks3
      from students
      group by Section
     ) tsum
     on t1.Section = tsum.Section and
        find_in_set(t1.Marks, tsum.Marks3) > 0
ORDER BY Section, Marks DESC, ID ASC;

输出:完全按照你的要求。;)

ID  NAME    SECTION MARKS   POINTS
1   S1  class1  55  5
7   S7  class1  32  3
3   S3  class1  25  1
10  S10 class2  78  5
14  S14 class2  78  5
6   S6  class2  66  3
2   S2  class2  33  1
13  S13 class2  33  1
4   S4  class3  65  5
11  S11 class3  65  5
5   S5  class3  43  3
12  S12 class3  43  3
15  S15 class3  25  1

小提琴

于 2013-08-02T07:24:09.247 回答