MySQL - >按条件选择平均值和平均值

时间:2014-10-17 13:54:50

标签: mysql mysqli

在我的查询中,我需要选择四个值 - 特定日期的平均值,平均值,特定日期的总计数和计数。我的查询现在仅用于平均值和计数。它需要有两个查询还是只能使用一个?

SELECT AVG(value) as average, 
COUNT(*) as noRates 
FROM `ratings` WHERE mid = 31

我希望的是

SELECT AVG(value) as average, 
COUNT(*) as noRates, 
AVG(value WHERE datecolumn = '2014-10-17') as averageToday, 
COUNT(* WHERE datecolumn = '2014-10-17') as noRatesToday 
FROM `ratings` 
WHERE mid = 31

1 个答案:

答案 0 :(得分:1)

对于条件平均值,您可以使用大小写和条件计数,您可以直接将表达式放在总和中,使其像计数函数一样表现

SELECT 
AVG(`value`) AS average, 
COUNT(*) AS noRates,
 AVG( CASE WHEN datecolumn = '2014-10-17' THEN `value` ELSE 0 END) AS averageToday,
 SUM(datecolumn = '2014-10-17') AS noRatesToday 
 FROM `ratings` 
 WHERE `mid` = 31