简体   繁体   English

SQL SUM和嵌套where子句

[英]SQL SUM and nested where clause

I have an SQL that takes an id, a start date and an end date as parameters. 我有一个将id,开始日期和结束日期作为参数的SQL。 I then sum certain that are restricted by the where clause. 然后,我总结一下受where子句限制的某些内容。 However I need to also sum the same column that doesnt take into account the data params and calculates the total for a particular driver. 但是,我还需要对不考虑数据参数的同一列求和,并计算特定驱动程序的总数。 For example: 例如:

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

So the SUM(Mileage) As MileageTotal ignores the where clause 因此,SUM(Mileage)As MileageTotal会忽略where子句

Try this: 尝试这个:

  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

Replace < table > with your actual table name ( Journey ???) < table >替换为您的实际表名( 旅程 ???)

Eliminate the where clause and do conditional summation: 消除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

I also added back in the from clause (presumably you left it out accidentally). 我还添加了from子句(大概是您无意中忽略了它)。

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

to

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

You may need to include more conditionals from the where clause -- I'm not sure which total you want. 您可能需要在where子句中包含更多条件-我不确定您想要的总数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM