SQL Rank列基于条件

时间:2017-08-30 19:28:10

标签: sql sql-server tsql select

RankFunction

从表格数据中我应该得出Rank列。 目的是根据以下条件选择Unique Duns:

  1. MAX(ConfidenceCode)
  2. 如果Confindencde相同,如果DeliveryAddressSeq = 0只有一行选择
  3. 如果Confindencde相同,如果DeliveryAddressSeq = 0有很多行,那么选择Customer of CustomerCode
  4. 所以,最后我需要Rank=1数据作为所需的输出

2 个答案:

答案 0 :(得分:1)

rank窗口函数可以解决这个问题:

SELECT Duns, ConfidenceCode, DeliveryAddressSeq, CustomerCode
FROM   (SELECT Duns, ConfidenceCode, DeliveryAddressSeq, CustomerCode,
               RANK() OVER (PARTITION BY duns
                            ORDER BY ConfidenceCode ASC,
                                     CASE DeliveryAddressSeq WHEN 0 THEN 0 
                                                             ELSE 1 
                                     END ASC,
                                     CustomerCode DESC) AS rk
        FROM   mytable)
WHERE  rk = 1

答案 1 :(得分:1)

Since you wanted to have the rank 1 only, you were looking for customercode 501, 504, 507

31|101|107|121                                                                                                                                                                                                                                         
32|191|156|127                                                                                                                                                                                                                                         
33|165|| 

Result

bal[i,j] <- bal[i,j-1] * (1 - spend) * marketReturns[i,j]