COUNT()MySQL中MAX()次数的出现次数

时间:2015-01-02 12:10:18

标签: mysql

我有一个捐款数据库和我针对它的一份报告我希望包括与最高捐款月份相等的捐款数量。例如,最高捐款月份可能是100美元,但可能有5人全部捐赠100美元,我想得到这个数字。

我目前的查询是:

SELECT SUM(mc_gross) AS Donations,
       SUM(mc_fee) AS Fees,
       COUNT(payment_date) AS DontationCount,
       COUNT(DISTINCT payer_email) AS DonatorCount,
       MAX(mc_gross) AS MaxDonation,
       @MaxD:=MAX(mc_gross),
       (
            SELECT COUNT(*)
            FROM #__paypal_donations
            WHERE MONTH(payment_date) = MONTH(CURDATE())
            AND YEAR(payment_date) = YEAR(CURDATE())
            AND mc_gross = @MaxD
       ) as MaxDonationMultiplier,
       AVG(mc_gross) AS AverageDonation
FROM #__paypal_donations
 WHERE MONTH(payment_date) = MONTH(CURDATE())
   AND YEAR(payment_date) = YEAR(CURDATE())

所以我认为我可能会很接近,但看起来我存储在@MaxD中用于子查询的值不起作用或者mc_gross = @MaxD中的比较本身不起作用,因为如果我替换@MaxD具有实际价值我得到了适当的数量。

1 个答案:

答案 0 :(得分:0)

您不能依赖于MySQL中表达式的赋值顺序。这使得像你这样的查询非常危险。幸运的是,您可以使用相关子查询轻松解决此问题:

SELECT SUM(mc_gross) AS Donations, SUM(mc_fee) AS Fees, COUNT(payment_date) AS DontationCount,
       COUNT(DISTINCT payer_email) AS DonatorCount, MAX(mc_gross) AS MaxDonation,
       (SELECT COUNT(*)
        FROM #__paypal_donations pd2
        WHERE MONTH(pd2payment_date) =  MONTH(pd.payment_date)) AND
              YEAR(pd2payment_date) = YEAR(pd.payment_date) AND
              pd2.mc_gross = MAX(mc_gross)
       ) as MaxDonationMultiplier,
       AVG(mc_gross) AS AverageDonation
FROM #__paypal_donations pd
WHERE MONTH(payment_date) = MONTH(CURDATE()) AND
      YEAR(payment_date) = YEAR(CURDATE());