0

这可能有点难以解释,但我的 SQL Server 数据库中有两列我已经简化了......

项目
ID
itemName
voteCount
分数

投票
itemID
得分

所以,基本上我存储了放在一个表中的每张选票,而且还计算了项目表中每个项目的投票数以及它的平均分数(满分 10 分)(我知道这是重复数据,但它让事情变得更容易)。

无论如何,我想创建一个 SQL 查询来查找得分最低的 2 个项目。你会认为这很容易,因为你只是这样做......

SELECT TOP 2 itemName FROM Items ORDER BY score ASC;

但是,客户端添加了以下复杂性。

当 2 个或更多项目得分相同时,10/10 票数最高的项目将被放置在上面。如果 2 个或更多项目具有相同的分数和相同的 10/10 票数,那么它将把获得最多 9/10 票的项目排在其他项目之上,依此类推,如果一切都正确,则一直到 0/10 票数否则是相等的。

所以,挑战是根据这些标准对所有项目进行排名,然后选择倒数 2。我已经尝试了分组、聚合和“子查询”的每一种组合来解决这个问题,但我认为我需要更聪明的人的帮助比我(如何,如何。

任何帮助将不胜感激。

澄清

一个项目的平均分数存储在项目表中,针对每个投票的分数保存在投票表中。最初,我们需要按平均分数(I.score)进行排名,如果 2 个项目具有相同的分数,我们需要开始计算与该项目相关的投票中 10/10 的数量(v.score)。

因此,我们可能有一个名为“t-shirt”的项目,其平均得分为 5/10。这来自 6 票,以下分数为 5,5,5,5,5,5。

下一个项目叫做“法拉利”,平均分也是5/10,但是这个项目只有4票,下面的分数是6,5,5,4

显然,法拉利应该赢,因为 sql 会看到它没有 10、没有 9、没有 8、没有 7,但它确实有 6 票,这比 T 恤要好。

4

1 回答 1

1
SELECT TOP 2 i.itemName 
FROM Items i
left outer join (
    select ItemID, 
        sum(case when score = 10 then 1 end) as Score10,
        sum(case when score = 9 then 1 end) as Score9,
        sum(case when score = 8 then 1 end) as Score8,
        sum(case when score = 7 then 1 end) as Score7,
        sum(case when score = 6 then 1 end) as Score6,
        sum(case when score = 5 then 1 end) as Score5,
        sum(case when score = 4 then 1 end) as Score4,
        sum(case when score = 3 then 1 end) as Score3,
        sum(case when score = 2 then 1 end) as Score2,
        sum(case when score = 1 then 1 end) as Score1
    from Votes
    group by ItemID
) v on i.ID = v.ItemID
ORDER BY i.score, 
    v.Score10,
    v.Score9,
    v.Score8,
    v.Score7,
    v.Score6,
    v.Score5,
    v.Score4,
    v.Score3,
    v.Score2,
    v.Score1
于 2010-02-02T02:30:11.953 回答