如何从我的MySQL表下方获得平均“费率”?

时间:2015-12-18 11:13:49

标签: mysql sql select group-by sum

我有一个带有这种结构的mysql表:

CREATE TABLE `item_rate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item` int(11) NOT NULL,
`ip` int(32) NOT NULL,
`rate` int(1) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `item` (`item`),
CONSTRAINT `item_rate_ibfk_1` FOREIGN KEY (`item`) REFERENCES `items` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

我需要从此表中获取此计算信息:

这里'rate'可能是1,2,3,4或5 所以我需要选择每个'项目' 和这个'项目' 计算

if rate = 5
5 * COUNT(id)
if rate = 4
4 * COUNT(id)

依旧......

示例:

在第1项上我有

rate 5 count 100
rate 4 count 311
rate 3 count 188
rate 2 count 83
rate 1 count 10

选择必须像这样计算

(5 * 100 + 4 * 311 + 3 * 188 + 2 * 83 + 1 * 10) / 692(sum of counts) = 3.58
然后围绕这个3.58 并返回这样的信息

item count
1    3
2    4
3    5
4    3
5    5

如何使用1个查询执行此操作?

P.S。我正在使用mysql db

3 个答案:

答案 0 :(得分:2)

看起来您只想要一个项目的平均评分。这最容易写成:

select item, avg(rate)
from item_rate
group by item;

如果您希望将其转换为小数点后两位,则转换为decimal或使用format()

select item, cast(avg(rate) as decimal(8, 2)) as avg_rate
from item_rate
group by item;

答案 1 :(得分:1)

试试这个:

SELECT item, FLOOR(SUM(rate * ratecount) / SUM(ratecount)) AS cnt
FROM (SELECT item, rate, COUNT(id) ratecount
      FROM item_rate 
      GROUP BY item, rate
     ) AS A
GROUP BY item;

要获取ip相关详细信息,请查看以下查询:

SELECT item, FLOOR(SUM(rate * ratecount) / SUM(ratecount)) AS cnt, 
       (CASE WHEN SUM(ipExists) > 0 THEN 1 ELSE 0 END) ipExists
FROM (SELECT item, rate, COUNT(id) ratecount, 
             SUM(CASE WHEN ip > 0 THEN 1 ELSE 0 END) ipExists
      FROM item_rate 
      GROUP BY item, rate
     ) AS A
GROUP BY item;

答案 2 :(得分:0)

在TSQL(MSSQL)中我会使用这样的东西:

DECLARE @i INT
DECLARE @total INT
DECLARE @number INT
SET @total = 0 
SET @number = 0
SET @i = 1  

WHILE (@i < 6)
BEGIN
SET @number = @number + (SELECT mt.countNumber FROM @MyTable mt WHERE mt.rate = @i) * @i
SET @total = @total + (SELECT mt.countNumber FROM @MyTable mt WHERE mt.rate = @i)
SET @i = @i+1
END

SELECT CAST(CONVERT(DECIMAL(10,3),@number)/CONVERT(DECIMAL(10,3),@total) AS DECIMAL(10,3))

输出为:3.590