2017-08-30 120 views
0

RankFunction基於條件的SQL等級列表

從表中的數據我應該得出Rank列。 目的是基於以下條件來選擇獨特鄧:

  1. MAX(ConfidenceCode)
  2. 如果Confindencde是一樣的,如果DeliveryAddressSeq = 0只有一個行選擇
  3. 如果Confindencde是一樣的,如果DeliveryAddressSeq = 0具有許多行,然後選擇CustomerCode的分鐘

所以,最後我需要Rank=1數據作爲期望的輸出

+0

閱讀如何從這裏申請排名https://blog.sqlauthority.com/2011/08/12/sql-server-tips-from-the-sql-joes-2-pros-development-series-ranking-functions- rank-dense_rank-and-row_number-day-12-of-35/ – Tassadaque

+0

如果Confindencde相同並且DeliveryAddressSeq!= 0會怎麼樣? –

+0

我知道如何申請Rank,但這不是海峽的前鋒。 –

回答

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

Mureinik,你真的好奇男人:-)我想知道如何在同等條件下排名。案件陳述的確有我正在尋找的訣竅 –

1

既然你想只在1級,你要找的customercode 501,504,507

SELECT duns, 
     confidencecode, 
     deliveryaddressseq, 
     customercode, 
     [rank] 
    FROM (SELECT *, 
       RANK() OVER (PARTITION BY duns 
           ORDER BY confidencecode DESC, 
             deliveryaddressseq, 
             customercode) AS [rank] 
      FROM t_duns) tt 
WHERE [rank] = 1 

結果

duns confidencecode deliveryaddressseq customercode rank 
1001 10    1     501    1 
1002 10    0     504    1 
1003 10    0     507    1