0

考虑一个投票系统。例如汽车。

  • 10 个人认为给汽车A打了 70% 的分数。
  • 1000人认为给汽车A打60%的分数。

因此,我们有值0.70.6您如何比较这些值?不用说,1000 票比 10 票更重要。最好,我想在SQL(使用AVG函数或类似函数)中有效地做到这一点。

这类问题应该有一个众所周知的公式。请帮忙!

4

1 回答 1

0

好,我们来数人。我们总共有 1010 人,其中 1000 人得分 60,而 10 人得分 70。

平均分是:

(1000 * 60 + 10 * 70)/(1000 + 10) = 60,09

现在将它们放到表中并对其运行查询:

create table scores (cust_id int identity(1,1), car char(1), score float);
go

------------------------------------------------------
declare @i int = 0;

while @i < 1000 
begin
    insert into scores(car, score) values ('A', 60.0);
    set @i = @i + 1
end

while @i < 1010
begin
    insert into scores(car, score) values ('A', 70.0);
    set @i = @i + 1
end;

------------------------------------------------------
select car, avg(score) [score], count(cust_id) [people_count]
from scores
group by car

结果:

car score   people_count
------------------------
A   60,09   1010

SQLFiddle


更新

create function compare_scores (@n1 int, @sc1 float, @n2 int, @sc2 float)
returns varchar(10)
as
begin
    return case when (@n1 * @sc1) <= (@n2 * @sc2) then (case when (@n1 * @sc1) = (@n2 * @sc2) then 'EQUAL' else 'LESS' end) else 'GREATER' end
end

----------------------------------------------------------
select dbo.compare_scores(10, 10.0, 1000, 8.0) [result]
union all
select dbo.compare_scores(10, 10.0, 10, 10.0) [result]
union all
select dbo.compare_scores(1000, 10.0, 10, 8.0) [result]

结果:

result
-------
LESS
EQUAL
GREATER
于 2013-08-09T19:22:54.330 回答