【问题标题】:TSQL: Ranking records by using different columnsTSQL:使用不同的列对记录进行排名
【发布时间】:2016-11-22 00:58:39
【问题描述】:

我有一张表格,上面有人员及其费用以及其他一些列。我需要的是创建两个新列:ranking1 和ranking2。这些排名是通过使用一些列和聚合来“计算”的。

ranking1: if total of person expenses exceeds 1000 then ranking 1 else ranking 0
ranking2: (if Col1 = 1 then 0 else 5) + (if Col2 = 1 then 0 else 7) + (if Col3 = 1 then 5 else 10)

我需要的是原始表(未更改),其中包含这两个新列,可以为我提供每个人的排名。

我的查询:

select Col1, Col2, Col3
       ((CASE Col1 = 1 THEN 0 ELSE 5 END) + 
        (CASE WHEN Col2 = 1 THEN 0 ELSE 7 END) + 
        (CASE WHEN Col3 = 1 THEN 5 WHEN Col3 = 2 THEN 2 ELSE 10 END)) as ranking, tmp.Expenses    from table t
left join (select id, Person, 
          (case when temp.expenses > 1000 then 1 else 0 end) as UserExpenses 
           from (select id, Person, sum(Expenses) as expenses 
           from table 
           group by id, Person) temp) tmp
on t.Person = tmp.Person and t.id = tmp.id
order by ranking desc, tmp.UserExpenses desc

我怀疑这个查询是否会给我我想要的东西,即带有两个新列作为排名的原始未更改表。特别是我对左连接持怀疑态度,它是右连接吗?提前致谢

【问题讨论】:

    标签: tsql join


    【解决方案1】:

    您的查询应该会给您带来正确的结果。以下是您的查询的简化版本:

    select  Col1,
            Col2, 
            Col3
            (CASE WHEN Col1 = 1 THEN 0 ELSE 5 END) + 
            (CASE WHEN Col2 = 1 THEN 0 ELSE 7 END) + 
            (CASE WHEN Col3 = 1 THEN 5 WHEN Col3 = 2 THEN 2 ELSE 10 END) as ranking, 
            (case when temp.expenses > 1000 then 1 else 0 end) as Expenses    
    from [table] t
    OUTER APPLY (select id, 
                        Person, 
                        sum(Expenses) as expenses 
                from [table] 
                where t.Person = Person and t.id = id
                group by id, Person
                ) temp
    order by ranking desc, temp.expenses desc
    

    【讨论】:

    • 感谢您的回答和建议!
    • 我的荣幸!如果有帮助就太好了!
    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多