是否可以通过一个查询获得所有这些统计数据?

时间:2011-05-05 22:34:18

标签: mysql statistics

我有一个投票评分系统,每个用户每天都可以对任何产品进行评分(每天最多10分,但他们每天可以使用相同的产品)。

我的投票表的架构如下: 投票:ID,user_id,product_id,得分,日期。

我想做的不仅仅是取得总得分和个人投票数量(所以我可以计算出平均值)而且还能获得独特的选民数量(DISTINCT user_id's )在当前时间范围内(在本例中为一个月)。我当前的查询是:

SELECT 
    SUM(`Vote`.`score`) AS `score`,
    COUNT(*) AS `votes`,
    CONCAT(YEAR(`Vote`.`date`), '-', MONTH(Vote.date)) AS `month`
FROM 
    `votes` AS `Vote`
WHERE 
    `product_id` = 4 
GROUP BY 
    month
ORDER BY `Vote`.`date` DESC 

提前致谢。

1 个答案:

答案 0 :(得分:4)

COUNT(DISTINCT user_id)列表中使用SELECT

您还可以计算AVG(score)

SELECT 
    SUM(score) AS totalScore,
    COUNT(*) AS totalVotes,
    COUNT(DISTINCT user_id) AS voters,
    AVG(score) AS averageScore,
    CONCAT(YEAR(`date`), '-', MONTH(`date`)) AS `month`
FROM 
    votes
WHERE 
    product_id = 4 
GROUP BY 
    `month`
ORDER BY `date` DESC