使用MAX()和SUM()聚合的SQL查询

时间:2013-12-10 12:44:21

标签: mysql sql sum max ms-access-2010

在这里和其他论坛上搜索了很多其他主题后,我似乎无法找到解决问题的方法。

我想要实现的目标是选择每家商店“花费最多”的帐户。

这是我到目前为止所得到的:

 SELECT MAX(s.Amount) MaxOfAmount
      , s.shopID
   FROM 
      ( SELECT SUM(OrderTotal) Amount
             , shopID
             , accountID 
          FROM Transactions 
         GROUP 
            BY shopID
             , accountID 
      ) s
  GROUP 
     BY s.shopID

这给了我每个shopID帐户花费的最多钱,但是我看不到与之关联的帐户ID。我尝试将selection.accountID添加到第一个选择。但是我必须将selection.accountID添加到“GROUP BY”子句中,这会产生与“FROM”查询相同的记录集。

我在这里完全不知所措,所以感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

请尝试这个应该可行。

 SELECT selection1.shopID,accountID,Amount
  FROM (SELECT SUM(OrderTotal) as Amount, shopID, accountID FROM Transactions GROUP BY     shopID, accountID )  AS selection1
  INNER JOIN
(
    SELECT Max(selection2.Amount) AS MaxOfAmount, selection2.shopID
    FROM (SELECT SUM(OrderTotal) as Amount, shopID, accountID FROM Transactions GROUP BY shopID, accountID )  AS selection2
    GROUP BY selection2.shopID
)
MAX_AMOUNT ON
    MAX_AMOUNT.MaxOfAmount=selection1.Amount AND
    MAX_AMOUNT.shopID=selection1.shopID

答案 1 :(得分:0)

我不确定,您可以在一个查询中执行此操作。或者这个查询会有些慢而不漂亮。

我通过子查询创建“view”或“#tmp_table”解决了同样的问题:

SELECT SUM(OrderTotal) as Amount, shopID, accountID INTO #shop_acc_amount FROM Transactions GROUP BY shopID, accountID

SELECT Max(selection.Amount) AS MaxOfAmount, selection.shopID,selection2.accountID
FROM #shop_acc_amount AS selection
JOIN #shop_acc_amount AS selection2 on selection2.shopID = selection.shopID AND selection2.Amount = Max(selection.Amount)
GROUP BY selection.shopID,selection2.accountID