【问题标题】:How to Rank Based on Multiple Columns如何根据多列进行排名
【发布时间】:2019-12-18 22:07:33
【问题描述】:

我正在尝试根据人们在特定类别中的计数对 Microsoft Access 中的人进行评分。

一个人可能有 7 种可能的类别,我想为每个人分配一个从 1 到 7 的分数,其中 1 分配给得分最高的类别,7 分配给最低的类别。他们可能没有针对每个类别的答案,在这种情况下可以忽略该类别。

目标是得到如下图所示的输出结果:

我尝试了一些不同的方法,包括分区和连接,但都没有奏效。老实说,我认为我一直在尝试的查询离题了。我尝试从头开始用 SQL 编写代码,并使用查询生成器。

非常感谢任何帮助!

【问题讨论】:

标签: sql ms-access


【解决方案1】:

由于您的电子邮件可能有重复计数,因此您需要两个子查询

SELECT 
    Score.email, 
    Score.category, 
    Score.[Count], 
        (Select Count(*) From Score As T Where 
            T.email = Score.email And 
            T.[Count] >= Score.[Count])-
        (Select Count(*) From Score As S Where 
            S.email = Score.email And 
            S.[Count] = Score.[Count] And 
            S.category > Score.category) AS Rank
FROM 
    Score
ORDER BY 
    Score.email, 
    Score.[Count] DESC, 
    Score.category;

【讨论】:

    【解决方案2】:

    对于 equal Count 值与 same email 的类别,以下将按字母顺序按 Category 名称降序排列记录(因为这是显示在您的示例中):

    select t.email, t.category, t.count,
    (
        select count(*) from YourTable u
        where t.email = u.email and 
        ((t.count = u.count and t.category <= u.category) or t.count < u.count)
    ) as rank
    from YourTable t
    order by t.email, t.count desc, t.category desc
    

    YourTable 的两个引用更改为您的表的名称。

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多