-1

我的桌子

+----+-------+------+---------+--------+------+
| ID | CLASS | NAME | SCHOOL  | POINTS | YEAR |
+----+-------+------+---------+--------+------+
|  1 |     5 | S1   | School1 |      5 | 2013 |
|  2 |     6 | S2   | School1 |      0 | 2013 |
|  3 |     5 | S3   | School2 |      1 | 2014 |
|  4 |     6 | S4   | School1 |      3 | 2013 |
|  5 |     6 | S5   | School2 |      1 | 2014 |
|  6 |     5 | S6   | School1 |      0 | 2013 |
|  7 |     6 | S7   | School2 |      3 | 2013 |
|  8 |     6 | S8   | School1 |      5 | 2013 |
|  9 |     5 | S9   | School1 |      1 | 2014 |
| 10 |     5 | S10  | School1 |      0 | 2013 |
| 11 |     6 | S11  | School2 |      5 | 2014 |
| 12 |     5 | S12  | School1 |      1 | 2013 |
+----+-------+------+---------+--------+------+

在这里,我想找到一所学校在班级和年级方面按最高分排序的总分。

我的问题,需要显示,5级,总分中也有6分。

我正在使用以下代码。

 SELECT School, SUM(Points) as Total  FROM students WHERE Year='2013' 
 GROUP BY School ORDER BY Total DESC LIMIT 6 

小提琴:http ://www.sqlfiddle.com/#!2/9b000/2

所以我的最终输出看起来:

 +---------+-------+
 | SCHOOL  | TOTAL |
 +---------+-------+
 | School1 |    14 |
   Class 5       6
   Class 6       8

 | School2 |     3 |
   Class 5       0
   Class 6       3
 +---------+-------+

请帮忙。对不起英语不好。

4

2 回答 2

0

这个查询应该这样做:

SELECT * FROM (
    SELECT 1 as seq, School, School AS Class, SUM(Points) as Total
      FROM students
     WHERE Year='2013'
     GROUP BY seq, School
   UNION
    SELECT 2 as seq, School, class, SUM(points) as total
      FROM students
     WHERE year='2013'
     GROUP BY seq, school, class
) AS temp
ORDER BY School, seq, Total DESC

http://www.sqlfiddle.com/#!2/9b000/37

注意:我相信您最好选择原始数据并让报告工具负责汇总和汇总数据。

于 2013-10-14T02:01:35.803 回答
0
select
row_number,
case when class = '' then School else Class end as School,
Total
from
(
    select
    @curRow := @curRow + 1 AS row_number,
    a.*
    from
        (
        SELECT 
        School, '' as Class, SUM(Points) as Total  
        FROM students WHERE Year = 2013
        group by School
        union all
        select
        School, Class, sum(Points) as Total
        from students where year = 2013
        group by
        School, Class
    ) a
    JOIN (SELECT @curRow := 0) r
    order by School, Class, Total desc
) a
order by row_number
于 2013-10-14T02:15:23.097 回答