左连接SQL Server返回结果基于排名

时间:2016-10-10 13:26:47

标签: sql sql-server sql-server-2008

我在SQL Server 2008中有一对多的左连接,需要根据查询中指定的优先级返回一行。为清楚起见,假设A是最重要的,其次是B,C ......

在我的表中,这些varchar字段是单词,不能按字母顺序排序,所以(我认为)我需要为每个字符分配一个数值。

Table1
Station 1
Station 2
Station 3


Table2 
Station 1   User 1  A
Station 1   User 2  B
Station 1   User 3  A
Station 1   User 4  B
Station 1   User 5  B
Station 2   User 1  B
Station 2   User 2  F
Station 2   User 3  D
Station 2   User 4  S
Station 2   User 5  E
Station 3   User 1  D
Station 3   User 2  D
Station 3   User 3  D
Station 3   User 4  S
Station 3   User 5  C

我想返回以下结果:

Station 1   A
Station 2   B
Station 3   C

即A对站1最重要,B对站2等最重要。

到目前为止,我的逻辑是使用case,min和select in statement:

select t1.station
, min(
case 
    when A then 1
    when B then 2
    when C then 3
    when D then 4
end
)
from table1.t1 left join table2.t2 on t1.station = t2.station
group by t1.station

但是,由于我通过连接返回多行,我不知道如何处理这个问题,我也希望返回字符串,而不是指定的优先级。我非常感谢您的帮助,提前致谢

2 个答案:

答案 0 :(得分:4)

您可以在ROW_NUMBER函数的CASE子句中使用ORDER BY表达式:

select station, mycol
from (
   select t1.station, t2.mycol,
          ROW_NUMBER() OVER (PARTITION BY t1.station
                             ORDER BY CASE t2.mycol
                                        WHEN A THEN 1
                                        WHEN B THEN 2
                                        WHEN C THEN 3
                                        WHEN D THEN 4
                                      end) AS rn
   from table1.t1 
   left join table2.t2 on t1.station = t2.station) as t
where t.rn = 1

查询将选择每个t1.station分区中具有最高优先级的记录。它还会返回table2

中的其他字段

答案 1 :(得分:1)

我认为您需要做的是使用Row_Number()函数来排序您的订单。如果您有任何问题,请与我联系:

https://msdn.microsoft.com/en-us/library/ms186734.aspx

https://msdn.microsoft.com/en-us/library/ms189461.aspx