我有一个查询需要为每个ID返回本月的最低余额。我得到的问题是它返回多个余额而不是余额的最小余额。 我不断得到这样的结果:
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
当我需要它返回最低余额时:
ID Name Month Year TodayMonth TodayYear BalMin
1 A 4 12 4 2012 10,000.00
这是我到目前为止所做的:
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
答案 0 :(得分:3)
你的group by
不应该包含余额(因为你正在运行min),你应该使用你在select中使用的datepart
(否则你不是月)。 left join
没有任何意义,因为无论如何你在where子句中寻找非空记录。这可能有效:
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
我已经删除了distinct
和top
个关键字,如您所见。 Distinct
通常不需要group by
(如果不是代码气味),我假设你的top
用于调试或订购视图,should probably not do。
答案 1 :(得分:0)
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, DATEPART(mm, History.ReportDate), Info.Name
ORDER BY History.ID
我没有检查过您的其他查询,但您的GROUP BY至少是问题的一部分。看一看。
答案 2 :(得分:0)
SELECT i.*, minbalance
FROM (
SELECT id, MIN(balance) AS minbalance
FROM history
WHERE reportDate >= DATEADD(day, -DAY(GETDATE()), CAST(GETDATE() AS DATE))
AND reportDate < DATEADD(month, 1, DATEADD(day, -DAY(GETDATE()), CAST(GETDATE() AS DATE)))
AND
GROUP BY
id
) b
JOIN info i
ON i.id = h.id