sql - Sum of 2 selects statement in sql with different where Clause
问题描述
I am trying to get the sum of 2 columns in one table but with different where the condition, the only difference is the amount per department is calculated based on 17% Margin. The Result should be the total revenue grouped by Event Name and Event ID.
for a sql Report, I have written 2 sql statements with different conditions and got the correct value for 2 columns but separately, i have summed both in a way but it was for one event.
SELECT EVT_ID, Event_Desc, Sum(Order_Total) as Total + (Select SUm(Order_Total *0.17) as Total from Orders Join Events EM On OrD.EVT_ID = EV.EVENTS_ID
where EVT_START_DATE between '2019-01-01' and '2019-01-31' Order_Department = 'FAB' )
From Orders Join Events EM On OrD.EVT_ID = EV.EVENTS_ID
where EVT_START_DATE between '2019-01-01' and '2019-01-31' Order_Department <> 'FAB'
Group by EVT_ID, Event_Desc
解决方案
select EVT_ID, Event_Desc, sum(Total)as Total
from
(
SELECT EVT_ID, Event_Desc, Sum(Order_Total) as Total
From Orders
Join Events EM On OrD.EVT_ID = EV.EVENTS_ID
where EVT_START_DATE between '2019-01-01' and '2019-01-31' and Order_Department <> 'FAB'
Group by EVT_ID, Event_Desc
union
Select EVT_ID, Event_Desc, SUm(Order_Total *0.17) as Total
from Orders
Join Events EM On OrD.EVT_ID = EV.EVENTS_ID
where EVT_START_DATE between '2019-01-01' and '2019-01-31' and Order_Department = 'FAB' ) tbl
Group by EVT_ID, Event_Desc
或者
SELECT EVT_ID, Event_Desc, Sum(case when Order_Department = 'FAB' then Order_Total else Order_Total *0.17 end ) as Total
From Orders
Join Events EM On OrD.EVT_ID = EV.EVENTS_ID
where EVT_START_DATE between '2019-01-01' and '2019-01-31'
Group by EVT_ID, Event_Desc
推荐阅读
- objective-c - 带有 Objective C 的静态库是否与任何版本的 XCode 兼容?
- python-3.x - 通过systemd服务调用脚本时导入rospy时导入错误
- c++ - 是否有用于计算带孔线性多边形面积的 CGAL 函数(Polygon_with_holes_2)?
- javascript - 单击时自动完成更新第二个输入框上的相同值
- python - 如何保存 IPython 显示
- python - 寻找一堆torch.Tensors的手段和标准(从ndarray图像转换而来)
- tkinter - 单击多个按钮后如何销毁我的 tkinter 标签?
- vue.js - 如何替换 Vuejs 中的标签元素?
- visual-studio-code - VSCode,禁用连字符
- elasticsearch - _search 查询如何在 Elasticsearch 中工作?