0

我有一个以 id、开始日期和结束日期作为参数的 SQL。然后我总结了某些受 where 子句限制的内容。但是,我还需要对不考虑数据参数的同一列求和,并计算特定驱动程序的总数。例如:

SELECT DISTINCT
PMTS.VolunteerId,
PMTS.ChargeRate,
SUM(
CASE [Type]
  WHEN 418 THEN Amount
  ELSE 0
END
) AS DriverMileage,
SUM(
CASE [Type]
  WHEN 1000 THEN Amount
  ELSE 0
END
) AS GPMileage,
SUM(
CASE [Type]
  WHEN 1001 THEN Amount
  ELSE 0
END
) AS Reimbursements,
SUM(
CASE [Type]
  WHEN 1002 THEN Amount
  ELSE 0
END
) AS MobilePhoneCharges,
SUM(Mileage) AS TotalMileageWeek,
B.TotalMileage,
VOLS.Address1,
VOLS.Address2,
VOLS.Town,
ISNULL(VOLS.Surname, '') + ', ' + ISNULL(VOLS.Forename, '') AS SurnameForename ,
ISNULL(VOLS.County, '') + ' ' + ISNULL(VOLS.PostCode, '') AS CountyPostcode 
FROM dbo.vVolunteerPayments PMTS
INNER JOIN dbo.vVolunteers VOLS ON PMTS.VolunteerId = VOLS.VolunteerID
--total mileage
INNER JOIN (select VolunteerId, sum(Mileage) as TotalMileage 
      FROM dbo.vVolunteerPayments GROUP BY VolunteerId) b ON 
b.VolunteerID=PMTS.VolunteerId
WHERE 
PMTS.VolunteerId = @volunteerid 
AND 
PMTS.PaymentEventID = 0
AND
PMTS.DateCreated BETWEEN @sd AND @ed
GROUP BY 
PMTS.VolunteerId
,Address1
,Address2
,Town
,County
,PostCode
,Surname
,Forename
,B.TotalMileage
,PMTS.ChargeRate

所以 SUM(Mileage) As MileageTotal 忽略 where 子句

4

2 回答 2

1

试试这个:

  Select 
    a.Name,
    SUM(Mileage) As MileageWeek,
    SUM(Mileage) As MileageTotal,
    b.TotMiles
    FROM <table> a
    JOIN (select name,sum(Mileage) as TotMiles 
          FROM <table> GROUP By name) b ON b.name=a.name
    WHERE
    Journey.DateCreated BETWEEN @startdate AND @enddate

替换< table >为您的实际表名(Journey ???)

于 2013-04-28T18:29:45.243 回答
0

消除where子句并进行条件求和:

Select Name,
       SUM(case when Journey.DateCreated BETWEEN @startdate AND @enddate then Mileage
                else 0
           end) As MileageWeek,
       SUM(Mileage) As MileageTotal
from Journey

我还在from子句中添加了回来(大概你不小心把它漏掉了)。

SUM(
CASE [Type]
  WHEN 418 THEN Amount
  ELSE 0
END
) AS DriverMileage,

sum(case when [type] = 418 and PMTS.DateCreated BETWEEN @sd AND @ed then amount
         else 0
    end) as DriverMileage

您可能需要从where子句中包含更多条件——我不确定您想要哪个总数。

于 2013-04-28T19:05:05.713 回答