mysql - 在另一列有效的基础上添加两列并重复使用
问题描述
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 来执行这些查询。
解决方案
在我的手机上,所以代码可能并不完美。您需要使用分组依据。希望这些能让你朝着正确的方向前进。
第一季度
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
推荐阅读
- memcached - MISP - Memcached 缺少项目
- javascript - 有没有办法将一个从 00 到 01、02 等的数字递增到 9,然后正常递增到 60?
- swiftui - SwiftUI MapKit 使用协调器 - 如何访问地图“视图”以调整“didUpdateLocations”中的可见区域?
- flutter - 找不到吸气剂:“上下文”。字体大小:MediaQuery.textScaleFactorOf(context)*18,
- excel - 如何使用 axlsx 向 Excel 单元格添加背景图案?
- parallels - 无法删除使用 prlctl 创建的“vm”
- appium - Appium Touch Action 长按不显示任何交互
- javascript - 反应将带有 onClick 事件的 html 标记添加到 innerHTML
- android - 时间对话框有额外的空白。是材料之一
- java - 无法在目标/生成源中生成类