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 by should not include balance (since you are running the min on it), and you should probably use the datepart that you are using in the select (otherwise you're not grouping by month). The left join doesn't make sense either since you are looking for non-null records in your where clause anyway. This might work:
SELECT History.ID,
Info.Name,
DATEPART(mm, History.ReportDate) AS [Month],
DATEPART(yy, History.ReportDate) AS [Year],
MIN(History.Balance) AS BalMin
FROM History
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,
DATEPART(mm, History.ReportDate),
DATEPART(yy, History.ReportDate),
Info.Name
ORDER BY History.ID
I've also removed the distinct and top keywords, as you can see. Distinct is often unnecessary with group by (if not a code smell) and I'm assuming your top was for debugging or ordering a view, which you should probably not do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With