TSQL:使用不同的列对记录进行排名

时间:2016-07-19 08:33:15

标签: tsql join

我有一张桌子上有人和他们的费用以及其他一些专栏。我需要的是创建两个新列: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

我怀疑这个查询是否会给我我想要的东西,这是原始的未更改的表,其中有两个新列作为排名。特别是我对左连接表示怀疑,这是正确的加入吗?提前致谢

1 个答案:

答案 0 :(得分:0)

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

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