[英]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. 我试图在一个表中获得2列的总和,但条件不同,唯一的区别是每个部门的金额是根据17%的保证金来计算的。 The Result should be the total revenue grouped by Event Name and Event ID.
结果应为按事件名称和事件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. 对于一个sql报表,我编写了2条具有不同条件的sql语句,并为2列获取了正确的值,但是分别地,我以一种方式对两者进行了求和,但这是针对一个事件的。
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
OR
要么
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
If I followed you correctly, you could approach this with conditional aggregation . 如果我正确地遵循了您的说明,则可以通过条件汇总来解决此问题 。 You can use a
CASE
construct within the SUM
aggregate function to check to which departement the current record belongs to and do the computation accordingly. 您可以在
SUM
聚合函数中使用CASE
构造来检查当前记录属于哪个部门并进行相应的计算。
SELECT
o.evt_id,
event_desc,
SUM(CASE
WHEN order_department = 'FAB' THEN order_total * 0.17
ELSE order_total END
) AS Total
FROM orders o
INNER JOIN events e On o.evt_id = e.events_id
WHERE evt_start_date BETWEEN '2019-01-01' and '2019-01-31'
GROUP BY
o.evt_id,
event_desc
NB: most columns in your query are not prefixed with a table alias, making it unclear from which table they come from. 注意:查询中的大多数列都不以表别名作为前缀,因此不清楚它们来自哪个表。 I added them when it was possible to make an educated guess from your sql code, and I would higly recommend that you add prefixes to all of the remaining.
当可以从您的sql代码中进行有根据的猜测时,我添加了它们,并且我建议您为所有其余代码添加前缀。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.