Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Summing up data in SQL

Status
Not open for further replies.

Deam

Programmer
Oct 10, 2000
68
0
0
US
I am selecting data from 3 different tables:

tEmp:(PersonID,FullName)
tBenefitHist:(PersonID,BenefitID,BenefitStartDate,BenefitEndDate,PlanCode)
tContributionHist:(PersonID,BenefitID,ContributionStartDate,ContributionEndDate,EmployerAmount)

I need to SUM the employeramounts(from table:tContributionHist)for each employee..this statement below is returning multiple rows...any suggestions will be greatly appreciated...


Declare @StartDate datetime,@EndDate datetime

Select @StartDate = '1/1/2006'
Select @EndDate = '1/1/2007'


SELECT distinct p.PersonID,p.FullName, SUM(EmployerAmount) as TotalEmployerAmount
FROM tEmp p
LEFT JOIN tBenefitHist bh
on bh.PersonID = p.PersonID
AND bh.BenefitStartDate BETWEEN @StartDate AND ISNULL(@EndDate, '99990101')
AND bh.BenefitStartDate = ((SELECT MAX(a2.BenefitStartDate)FROM tBenefitHist a2 WHERE a2.PersonID = bh.PersonID))
LEFT JOIN tContributionHist pbch
ON bh.PersonID = pbch.PersonID
AND bh.BenefitID = pbch.BenefitID
AND ContributionStartDate =(SELECT MAX(b2.ContributionStartDate)FROM tContributionHist b2
WHERE b2.PersonbenefitID = bh.PersonbenefitID)
WHERE AND pbch.ContributionStartDate =
(SELECT MAX(b2.ContributionStartDate)FROM tContributionHist b2 WHERE b2.PbenefitID = bh.benefitID )
Group by p.PersonID,p.FullName,pbch.PersonID,bh.PersonID,bh.BenefitID,pbch.BenefitID,ContributionStartDate
order by p.fullname

 
Hi,

I don't really know the content of the tables but what I see is that you've added the ContributionStartDate field to the group by clause.

Try your query without this field in the group by and see what it does.

Greetz,

Geert


Geert Verhoeven
Consultant @ Ausy Belgium

My Personal Blog
 
That did not do the trick...any other suggestions
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top