COUNT() MySQL 中 MAX() 出现的次数
COUNT() the number of MAX() occurrences in 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 替换为实际值,我会得到正确的计数。
您不能依赖 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());
我有一个捐赠数据库和我针对它运行的报告之一我想包括等于最大捐赠月数的捐赠数量。比如一个月最高捐款可能是$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 替换为实际值,我会得到正确的计数。
您不能依赖 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());