我有两个表费用和员工。我想获得每位员工的总费用,以及已退款的总费用。退款定义为1,未退款为0.
目前,我的查询返回以下内容,但应该为每位员工添加值并仅返回一行:
select distinct(emp.employeeid) as EmpID, sum(ex.amount) as TotalExpenses,
(select SUM( ex.amount ) where ex.Refunded =1) as refunded,
(select SUM( ex.amount ) where ex.Refunded =0) as notrefunded
from Expenses ex
left outer join Employee emp
on ex.EmployeeID = emp.EmployeeID
group by emp.employeeid,ex.amount, ex.Refunded
48 10.00 10.00 NULL
48 16.00 NULL 16.00
49 2.00 2.00 NULL
49 10.00 NULL 10.00
答案 0 :(得分:4)
这是子查询的一种奇怪用法,使用distinct
时不需要group by
。我想这是你想要的查询:
select emp.employeeid as EmpID, sum(ex.amount) as TotalExpenses,
sum(case when e.Refunded = 1 then ex.amount else 0 end) as refunded,
sum(case when e.Refunded = 0 then ex.amount else 0 end) as notrefunded
from Employee emp left outer join
Expenses ex
on ex.EmployeeID = emp.EmployeeID
group by emp.employeeid;
注意:我改变了left outer join
的顺序。您按员工ID进行分组。似乎不太可能为不存在的员工支付费用。无论如何,汇总是emp.employeeid
,表明你真的希望匹配。
答案 1 :(得分:2)
@Gordon Linoff的答案是理想的解决方案。但是,它并没有解决您在初始查询中犯的一些错误。
Distinct
是select
语句的子句,而不是函数。它始终适用于所有返回的字段。使用相关子查询(即列列表中出现的子查询)时,需要将子查询连接到主查询并分别查询表。如上所述,您只能获取该行中找到的值sum
。要正确地做到这一点,它需要是这样的:
(select SUM( ex2.amount )
from Expenses ex2
where ex2.Refunded =1
and ex2.employeeid = e.ex2.employeeid) as refunded