2017-06-14 45 views
1

我有一個要求來設置每個文檔類型的出現次數並根據文檔名稱進行排序。任何機會在MS SQL 2008如何做到這一點?在SQL中設置事件

這裏的情景:

  1. 如果文檔類型是獨一無二的,更新文件名的出現次數爲001
  2. 如果文檔類型是不是唯一的,檢查了6最後一位文檔名稱的權利,並將其與具有相同文檔類型的其他文檔名稱進行比較。請根據預期產出查看當前表格。

當前表。

EE. Number DocumentType Document name     
406453  Transfer  ITransfers 20170531 154323  
406453  Offer Letter Amendments 20170601 092848    
406453  Offer Letter Amendments 20170601 092500  
406433  Misc   Misc. 20170531 153348 
406453  Offer Letter Amendments 20170601 092735 

期望輸出

EE. Number DocumentType Document name     occurrence number 
406453  Transfer  ITransfers 20170531 154323 001 
406433  Misc   Misc. 20170531 153348   001 
406453  Offer Letter Amendments 20170601 092735 001 
406453  Offer Letter Amendments 20170601 092848 002 
406453  Offer Letter Amendments 20170601 092500 003 
+1

正在使用的是何種RDBMS? –

+0

我正在使用MS SQL 2008. – yope

回答

1

如果我理解正確的,你想row_number()

select t.*, 
     row_number() over (partition by document_type 
          order by right(document_name, 6) 
         ) as occurrence_number 
from t; 

這將返回一個整數,不帶前導零的字符串。您可以將數字轉換爲任何數據庫中的字符串;確切的功能取決於您使用的數據庫。

編輯:

您可以將此轉換爲左填充的字符串:

select t.*, 
     right('000' + 
      cast(row_number() over (partition by document_type 
            order by right(document_name, 6) 
            ) as varchar(255) 
       ) as occurrence_number 
from t; 
+0

你好,這不是行號。但我需要根據文檔類型和文檔名稱設置出現次數。 – yope

+0

好吧,那可行!謝謝! – yope

+0

如何在row_number()的前綴上添加00?我嘗試了'00'+ row_number()但不起作用。 – yope