3

我有一个查询需要为每个 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
4

3 回答 3

3

group by不应该包括余额(因为您正在运行 min ),并且您可能应该使用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

如您所见,我还删除了distinctand关键字。通常是不必要的(如果不是代码味道),我假设您是用于调试或订购视图,您可能不应该这样做topDistinctgroup bytop

于 2012-04-20T14:16:20.213 回答
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 至少是问题的一部分。看一看。

于 2012-04-20T14:16:18.693 回答
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
于 2012-04-20T14:33:38.420 回答