带有SUM和最新日期的GROUP BY

时间:2016-10-26 14:01:14

标签: sql tsql group-by

我有以下查询

SELECT 
 TableA.MaterialCode, 
 TableB.LotNumber, 
 SUM(TableB.Quantity) AS Quantity, 
 CONVERT(varchar(25), TableC.IssueDate, 121) AS IssueDate
FROM TableA
INNER JOIN
 TableB ON TableA.PONumber = TableB.PONumber 
INNER JOIN
 TableC ON TableA.PONumber = TableC.PONumber
WHERE TableC.VendorID = 'VendorID'
AND TableC.IssueDate > '10/25/2016  9:47:53 AM'
GROUP BY MaterialCode, LotNumber, IssueDate
ORDER BY TableC.IssueDate DESC

返回如下数据集:

╔══════════════╦═══════════╦══════════╦═════════════════════════╗
║ MaterialCode ║ LotNumber ║ Quantity ║        IssueDate        ║
╠══════════════╬═══════════╬══════════╬═════════════════════════╣
║        12345 ║   3451972 ║       55 ║ 2016-10-25 10:48:13.210 ║
║        12346 ║   3436055 ║       32 ║ 2016-10-25 09:57:26.693 ║
║        12346 ║   3436055 ║      224 ║ 2016-10-25 09:47:54.077 ║
╚══════════════╩═══════════╩══════════╩═════════════════════════╝

我想扩展这个,而不是通过IssueDate进行分组,只是获取组中的最新日期。我已经尝试了下面的代码,但它会抛出错误...because it is not contained in either an aggregate function or the GROUP BY clause.

SELECT 
 TableA.MaterialCode, 
 TableB.LotNumber,
 SUM(TableB.Quantity) AS Quantity, 
 MAX(CONVERT(varchar(25), TableC.IssueDate, 121)) AS IssueDate
FROM TableA
INNER JOIN
 TableB ON TableA.PONumber = TableB.PONumber 
INNER JOIN
 TableC ON TableA.PONumber = TableC.PONumber
WHERE TableC.VendorID = 'VendorID'
AND TableC.IssueDate > '10/25/2016  9:47:53 AM'
GROUP BY MaterialCode, LotNumber
ORDER BY TableC.IssueDate DESC

以下是我希望通过以上查询获得的输出:

╔══════════════╦═══════════╦══════════╦═════════════════════════╗
║ MaterialCode ║ LotNumber ║ Quantity ║        IssueDate        ║
╠══════════════╬═══════════╬══════════╬═════════════════════════╣
║        12345 ║   3451972 ║       55 ║ 2016-10-25 10:48:13.210 ║
║        12346 ║   3436055 ║      256 ║ 2016-10-25 09:57:26.693 ║
╚══════════════╩═══════════╩══════════╩═════════════════════════╝

如何更改查询以实现上述数据集?

1 个答案:

答案 0 :(得分:1)

您的查询应该是

SELECT 
     a.MaterialCode, 
     b.LotNumber, 
     SUM(b.Quantity) AS Quantity, 
     CONVERT(varchar(25), MAX(c.IssueDate), 121) AS MaxIssueDate
FROM TableA a
INNER JOIN
    TableB b ON a.PONumber = b.PONumber 
INNER JOIN
    TableC c ON a.PONumber = c.PONumber
WHERE c.VendorID = 'VendorID'
    AND c.IssueDate > '10/25/2016  9:47:53 AM'
GROUP BY a.MaterialCode, b.LotNumber
ORDER BY MaxIssueDate DESC;

如上所述,如果您想在结果集中加入a.PONumber,请将其添加到GROUP BY子句中。

SELECT MAX(CONVERT(varchar(25), TableC.IssueDate, 121)) AS IssueDate不是问题,这里的问题是你的ORDER BY子句。

您可以使用ORDER BY MAX(CONVERT(varchar(25), TableC.IssueDate, 121)),但最好只使用上述代码中的ORDER BY MaxIssueDate