I have a query which needs to return the lowest balance for this month for each ID. The problem I am getting is it is returning multiple balances instead of the min balance on Balance.
I keep getting results like these:
ID Name Month Year TodayMonth TodayYear BalMin
1 A 4 12 4 2012 10,000.00
1 A 4 12 4 2012 20,000.00
When I need it to return just the lowest Balance:
ID Name Month Year TodayMonth TodayYear BalMin
1 A 4 12 4 2012 10,000.00
Here is what I have so far:
SELECT DISTINCT
TOP (100) PERCENT History.ID, info.Name, DATEPART(mm, History.ReportDate) AS Month, DATEPART(yy,History.ReportDate) AS Year, DATEPART(mm, { fn CURDATE() }) AS TodayMonth, DATEPART(yy, { fn CURDATE() }) AS TodayYear, MIN(History.Balance) AS BalMin
FROM History LEFT OUTER JOIN Info ON History.ID = Info.ID
WHERE (DATEPART(yy, History.ReportDate) = DATEPART(yy, { fn CURDATE() })) AND (DATEPART(mm, History.ReportDate) = DATEPART(mm,
{ fn CURDATE() })) AND (History.Balance > 0)
GROUP BY History.ID, History.ReportDate, Info.Name, History.Balance
ORDER BY History.ID
Your
group byshould not include balance (since you are running the min on it), and you should probably use thedatepartthat you are using in the select (otherwise you’re not grouping by month). Theleft joindoesn’t make sense either since you are looking for non-null records in your where clause anyway. This might work:I’ve also removed the
distinctandtopkeywords, as you can see.Distinctis often unnecessary withgroup by(if not a code smell) and I’m assuming yourtopwas for debugging or ordering a view, which you should probably not do.