首页 > 解决方案 > 在另一列有效的基础上添加两列并重复使用

问题描述

id  discount    ref_name    ref_type
101 12          Sid         national
104 34          Buny        international
108 21          Amir        national
196 35          Sanjeev     local
232 23          Anurag      local
345 2           Abhitab     international

Q1。如何获得每个 ref_type 的总折扣?

Expected result
national 33 (12+21)
international 36 (34+2)
local 58 (35+23)

我的查询

select ref_type,sum(discount) from student where ref_type ='local'  UNION ALL 
select ref_type,sum(discount) from student where ref_type ='national' UNION ALL 
select ref_type,sum(discount) from student where ref_type ='international' ;

Q2。通过汇总单个参考类型提供的所有折扣获得第三高折扣?答案national 33

Q3。显示所有超过 50 条的记录?和local 58

对于这两个,我打算用上面的结果查询制作一个表并放置 where 条件。但我确信我选择的方式不是正确的,我想知道实现目标的更好方式。我正在使用 MySQL 来执行这些查询。

标签: mysql

解决方案


在我的手机上,所以代码可能并不完美。您需要使用分组依据。希望这些能让你朝着正确的方向前进。

第一季度

Create table temp1 Select ref_type, sum(discount) as 
total_discount from table group by ref_type

第二季度

Create table q2 (id int auto_increment primary key, 
ref_type varchar(50), total_discount int)

Insert into q2 (ref_type, total_discount) select ref_type, 
total_discount from temp1 order by total_discount;

Select * from q2 where id=3

第三季度

Select * from q2 where total_discount>50

推荐阅读