我已经写了这个查询。它可以工作,但是 TotalCost 对于不同的参数保持不变。我希望它相应地更改其值。当前,它采用所有行的总和,但只应采用查询返回的行的总和。
alter PROCEDURE [dbo].[ServicesDetailedReportPartyWise]
@FromDate date= '01/Jun/2010',
@ToDate date= '01/Oct/2018',
@PartyName varchar(20)='B'
AS
BEGIN
Set @ToDate= ISNULL(@ToDate, getdate());
Select inv.InvoiceNo, Convert(varchar(11),inv.EntryDateTime,106) as EntryDateTime, s.ServiceName, c.VehicleRegNo, inv.ServicePrice, c.CustomerName, inv.Party as PartyName,
inv.fk_BookingID, t.TotalCost, SUM(t.TotalCost) over () as TotalRevenue, ISNULL(SUM(inv.OwnerCommission) over(),0) as TotalCommission, ISNULL(inv.OwnerCommission,0) as Commission
from dbo.[Services] s
inner join invoices inv
on inv.fk_ServiceID= s.ServiceID
inner join customers c
on c.CustomerID= inv.fk_CustomerID
Cross join (Select SUM(inc.ServicePrice) as TotalCost from dbo.Invoices inc) t
where inv.Party= @PartyName AND (convert(date, inv.EntryDateTime) between @FromDate and @ToDate)
order by inv.EntryDateTime desc
END
答案 0 :(得分:1)
TotalCost
是t.TotalCost
,其中t
的定义是:
(Select SUM(inc.ServicePrice) as TotalCost from dbo.Invoices inc) t
此子查询根本没有过滤,它只是整个dbo.Invoices
表中的总和-它是一个单元格,然后您已将其交叉连接到所有行。
所以:这就是为什么它没有改变。
如果您希望总和超过inv
,则需要对各组进行分组和求和。
答案 1 :(得分:0)
您的cross join
对过滤不进行任何操作,如果要这样做,则需要进行类似于outer query
的过滤。
其他选择是应用 window 函数:
select inv.InvoiceNo, Convert(varchar(11),inv.EntryDateTime,106) as EntryDateTime,
s.ServiceName, c.VehicleRegNo, inv.ServicePrice, c.CustomerName, inv.Party as PartyName,
inv.fk_BookingID,
sum(inv.TotalCost) over (partition by . . .) as TotalCost,
sum(inv.TotalCost) over () as TotalRevenue,
isnull(sum(inv.OwnerCommission) over(), 0) as TotalCom
mission, isnull(inv.OwnerCommission,0) as Commission
. . .