C1 - 比赛1,C2 - 比赛2,C3 - 比赛3。 C1Points - Compeletion1Points
此表代表一个分数表,其中不同类别的学生参加不同类型的比赛。
C1,C2,C3栏是比赛的名称,如果学生参加比赛的价值为“1”。如果'0'他没有参加。
S1 to S15 : Student Names
C1 ,C2,C3 : Competition Names
Section : Indicates category of that particular student
C1points, C2points, C3points : Points received by the particular student in that particular competition
在这里,我想按点和比赛名称降序对每个部分进行分组。
请注意:C1需要更改比赛1,C2 - 比赛2,C3 - 比赛3
请参阅:http://www.sqlfiddle.com/#!2/20920/1
我的最终输出看起来像
答案 0 :(得分:1)
仅适用于第1部分。您可以类似地实现第2节和第3节的逻辑
select *
from
(
select s1.ID,
s1.Name,
'Competition 1' as Competition,
s1.C1Points as Points
from students s1
where SECTION='Section1'
and ifnull(s1.C1,'')<>''
and s1.C1Points<>0
union
select s2.ID,
s2.Name,
'Competition 2' as Competition,
s2.C2Points as Points
from students s2
where s2.SECTION='Section1'
and ifnull(s2.C2,'')<>''
and s2.C2Points<>0
union
select s3.ID,
s3.Name,
'Competition 3' as Competition,
s3.C3Points as Points
from students s3
where s3.SECTION='Section1'
and ifnull(s3.C2,'')<>''
and s3.C3Points<>0
)t
order by t.points desc,t.Competition desc
<强> SQl Fiddle 强>
答案 1 :(得分:1)
您可以尝试使用以下查询来合并所有部分:
select ID,name,comp_desc,points
from (
select section,ID,name, 'Competion1' as comp_desc, C1Points as points
from students
union
select section,ID,name, 'Competion2' as comp_desc, C2Points as points
from students
union
select section,ID,name, 'Competion3' as comp_desc, C3Points as points
from students
) t
where points <> 0
group by section, name,comp_desc, points
order by section, points desc, comp_desc desc;
虽然我仍然认为您显示的输出需要更多描述。例如,由Luv确定为什么在第1部分中,S13竞赛2在3之前出现。再次针对第2部分,为什么S14将在S10之前进入竞争2。
但是,我认为您现在可以修改上述查询以满足您的需求。
答案 2 :(得分:0)
select * from
(select
section
,id
,name
,"Competition 1" as Competition
,C1Points as Points
from
students
where
C1 = 1
union
select
section
,id
,name
,"Competition 2" as Competition
,C2Points as Points
from
students
where
C2 = 1
union
select
section
,id
,name
,"Competition 2" as Competition
,C2Points as Points
from
students
where
C3 = 1
) agg
order by
section, points desc