我的桌子
+----+-------+------+---------+--------+------+
| 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
+---------+-------+
请帮忙。对不起英语很差。
答案 0 :(得分: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
注意:我相信您最好选择原始数据,并让报告工具负责汇总和汇总数据。
答案 1 :(得分: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