在MySql的同一表中加入2个选择查询

时间:2019-03-04 05:07:24

标签: mysql sql select new-operator

我有一个名为tbl_events的表名,它确实具有以下列

Id,事件名称,地区,分支类型,点数

我需要一个总和列,其中Branch_Type = 2;和点的总和除以10,其中Branch_Type = 2之后,我必须将这两个值和组相加,然后按地区和按Desc排序。我尝试了此查询,但似乎出现了问题,请问有人可以帮忙吗?

Select (t1.B_Points + t2.D_Points) as T_Points,District From 
(Select Sum(Points)*.1 as B_Points ,District From tblstudents Where Branch_Type=3 group by District)t1
Left Join(Select Sum(Points) as D_points, District From tblstudents Where Branch_Type=2 group by District)t2 on 
(t1.District=t2.District) Order by Desc

2 个答案:

答案 0 :(得分:0)

您需要按以下顺序添加列别名T_Points

Select (t1.B_Points + t2.D_Points) as T_Points,District 
From 
(
  Select Sum(Points)*.1 as B_Points ,District From tblstudents 
  Where Branch_Type=3 group by District
)t1
Left Join
(
  Select Sum(Points) as D_points, District From tblstudents 
  Where Branch_Type=2 group by District
)t2 on t1.District=t2.District
 Order by T_Points Desc

答案 1 :(得分:0)

您似乎只想条件聚合:

select district,
       sum(case when branch_type = 3 then 0.1 * points
                when branch_type = 2 then points
                else 0
           end) as t_points
from tblstudents
group by district;

如果要按降序排序,请添加:

order by t_points desc

注意:这假设您要的是既没有分支类型又没有分区的地区。如果这不是问题,请将逻辑移至where子句:

select district,
       sum(points * (case when branch_type = 3 then 0.1 else 1.0 end) as t_points
from tblstudents
where branch_type in (2, 3)
group by district
order by t_points desc;