我试图在一张表中获得2列的总和,但条件不同,唯一的区别是每个部门的金额是根据17%的保证金计算的。 结果应为按事件名称和事件ID分组的总收入。
对于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
答案 0 :(得分:1)
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
答案 1 :(得分:0)
如果我正确地跟随了您,则可以使用条件汇总来解决此问题。您可以在CASE
聚合函数中使用SUM
构造来检查当前记录属于哪个部门并进行相应的计算。
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:查询中的大多数列都没有前缀表别名,因此不清楚它们来自哪个表。当可以从您的sql代码中进行有根据的猜测时,我添加了它们,并且我建议您为所有其余的代码添加前缀。