我有一個SQL,它將一個ID,開始日期和結束日期作爲參數。然後我總結一下受where子句的限制。不過,我也需要總結同一列,不考慮數據參數並計算特定驅動程序的總數。例如:SQL SUM和嵌套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(里程)作爲MileageTotal忽略where子句
我可能需要這樣做,因爲我只能有一個記錄集返回,否則返回報表控件生成新頁面 – amun1000 2013-04-28 20:47:47
我已更新查詢以顯示全文 - 任何建議乾杯 – amun1000 2013-04-28 21:18:08
乾杯戈登 - 多數民衆贊成在! – amun1000 2013-04-28 22:21:20