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

问题描述 投票:0回答:2

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

Id,Event_Name,District,Branch_Type,Points

我需要一个Points of Points列,其中Branch_Type = 2;并且除以10之后,其中Branch_Type = 2,之后我必须按区域和顺序添加这两个值和组结果。我试过这个查询,但似乎有问题任何人都可以帮忙吗?

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
mysql sql select new-operator
2个回答
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

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;
© www.soinside.com 2019 - 2024. All rights reserved.