2013-04-28 133 views
0

我有一個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子句

回答

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條款更多條件句 - 我不知道你想要的總數。

+0

我可能需要這樣做,因爲我只能有一個記錄集返回,否則返回報表控件生成新頁面 – amun1000 2013-04-28 20:47:47

+0

我已更新查詢以顯示全文 - 任何建議乾杯 – amun1000 2013-04-28 21:18:08

+0

乾杯戈登 - 多數民衆贊成在! – amun1000 2013-04-28 22:21:20

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>與您的實際表名(之旅 ??? )

+0

非常感謝你 – amun1000 2013-04-28 19:04:46

+0

我認爲這可能是答案,但它返回兩個記錄集。我需要爲報告提供單獨的記錄集報告。我將解決方案綁定在下面,但是這又返回了多個記錄集並 – amun1000 2013-04-28 21:10:18

+0

我更新了查詢以顯示全文 - 任何建議Cheers – amun1000 2013-04-28 21:17:00