SQL Group By语句,分组数据的最大值

时间:2014-02-03 02:39:24

标签: sql ms-access group-by aggregate-functions

我的问题类似于此问题SQL Group By Having Where Statements,唯一的区别是我需要在指定日期生成所有ProductIds的最新数量,例如 ProductId 1 on 15-Feb-12 is 100&的数量ProductId 2 on 15-Feb-12 is 200ProductId 1 on 15-Mar-12 is 150的数量& ProductId 2 on 15-Mar-12 is 250。从MS Access表跟踪月末的产品数量,如下所示。

ProductId | ReportingDate | Quantity|  
1         | 31-Jan-12     | 100     |  
2         | 31-Jan-12     | 200     |  
1         | 28-Feb-12     | 150     |  
2         | 28-Feb-12     | 250     |  
1         | 31-Mar-12     | 180     |  
2         | 31-Mar-12     | 280     |

2012年3月15日上我想要的输出应该是如下查询:

ProductId | ReportingDate | Quantity|  
1         | 28-Feb-12     | 150     |  
2         | 28-Feb-12     | 250     |  

我当前的SQL语句只返回一个ProductID的结果。任何人都可以帮我扩展查询以显示所有ProductIds吗?

SELECT TOP 1 Sheet1.ProductId, Sheet1.ReportingDate AS MaxOfReportingDate, Sheet1.Quantity
FROM Sheet1
WHERE (Sheet1.ProductId = 1)
AND (Sheet1.ReportingDate < #2012/03/15#)
ORDER BY Sheet1.ReportingDate DESC

1 个答案:

答案 0 :(得分:0)

您需要加入一个子查询,该子查询列出了所需日期之前的最新日期:

SELECT
Sheet1.ProductId, Sheet1.ReportingDate, Sheet1.Quantity
FROM Sheet1 INNER JOIN
(SELECT Sheet1.ProductId, MAX(Sheet1.ReportingDate) AS MaxOfReportingDate
FROM Sheet1
WHERE ReportingDate < #2012/03/15#
GROUP BY ProductId) AS a 
ON Sheet1.ProductId = a.ProductId AND Sheet1.ReportingDate = a.MaxOfReportingDate
ORDER BY Sheet1.ReportingDate DESC