我不确定您的问题是关于如何创建函数或查询的外观。我会回答后者。
让我假设你有一个合理的数据结构,有四个表:( Patients
未使用);Operations
(每位患者的手术清单);OperationSupplies
(每个操作的供应清单);和Supplies
(有关每个供应的信息)。
select coalesce(sum(os.quantity * s.cost), 0) as TotalCost
from Operations o left outer join
OperationSupplies os
on os.OperationId = o.OperationId left outer join
Supplies s
on s.SupplyId = os.SupplyId
where o.PatientId = @PatientId
这是作为函数的结构:
create function xxx (@PatientId int)
returns float
as
begin
declare @val float;
select @val = coalesce(sum(os.quantity * s.cost), 0) as TotalCost
from Operations o left outer join
OperationSupplies os
on os.OperationId = o.OperationId left outer join
Supplies s
on s.SupplyId = os.SupplyId
where o.PatientId = @PatientId;
return(@val);
end;