繁体   English   中英

按Points和CompetitionName降序对每个Sections进行分组

[英]Group each Sections by Points and CompetitionName descending order

在此输入图像描述

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

我的最终输出看起来像

在此输入图像描述

仅适用于第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小提琴

您可以尝试使用以下查询来组合所有部分:

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。

但是,我认为您现在可以修改上述查询以满足您的需求。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM