为什么存储过程为每个组返回错误的总和?

时间:2018-11-22 11:16:59

标签: sql sql-server tsql stored-procedures

我有此查询,但SUM(SUM(inv.ServicePrice)) over () as TotalRevenueAllServices 把错误的钱还给我。我实际上想获取我为每个组完成的所有总和,但返回错误的值。

Select top(3) s.ServiceName, Count(inv.fk_ServiceID) as TotalServicesCount, Sum(inv.ServicePrice) TotalServicesRevenue,
        SUM(SUM(inv.ServicePrice)) over () as TotalRevenueAllServices
        from Invoices inv
        inner join Services s
        on s.ServiceID= inv.fk_ServiceID
        group by inv.fk_ServiceID, s.ServiceName
        Order By ServiceName asc

1 个答案:

答案 0 :(得分:0)

declare @FromDate date= '22/Nov/2017',
        @ToDate date= '24/Nov/2018'


        Set @ToDate= ISNULL(@ToDate, getdate());


        with MainTable
        as
        (
        Select top(3) s.ServiceName, Count(inv.fk_ServiceID) as TotalServicesCount, Sum(inv.ServicePrice) TotalServicesRevenue      
        from Invoices inv
        inner join Services s
        on s.ServiceID= inv.fk_ServiceID
        --where CAST(inv.EntryDateTime as DATE) between @FromDate and @ToDate
        group by inv.fk_ServiceID, s.ServiceName
        Order By ServiceName asc
        )
        select * , (select sum(totalservicesrevenue) from MainTable) 'AllServicesRevenue'
        ,          (select sum(TotalServicesCount) from MainTable) 'OverallServices'
                    from MainTable