2017-04-03 22 views
3

我想問一個SQL問題(我目前正在使用SQL Server Management Studio)。SQL Server:根據記錄中的其他字段添加參考號

CustomerID  ProductID   ProductName 
------------------------------------------------------ 
111     6577    ProductA 
111     6123    ProductB  
111     1133    ProductC 
111     1133    ProductC  
222     6577    ProductA  
222     6577    ProductA  
222     1578    ProductL  
333     9273    ProductX 

和結果,這將取決於在客戶和產品ID添加參考號中的其他列中。(對於相同的客戶ID,如果產品ID是不同的基準數將遞增)

CustomerID  ProductID   ProductName  ref 
----------------------------------------------------------- 
111     6577    ProductA   111-1 
111     6123    ProductB   111-2 
111     1133    ProductC   111-3 
111     1133    ProductC   111-3 
222     6577    ProductA   222-1 
222     6577    ProductA   222-1 
222     1578    ProductL   222-2 
333     9273    ProductX   333-1 

我不知道如何通過比較productid來添加參考號?

使用dense_rank()預先感謝您

回答

2

select * 
    , ref = convert(varchar(13),customerid) + '-' 
     + convert(varchar(13),dense_rank() over (partition by customerid order by productname)) 
from t 

rextester演示:http://rextester.com/UBXR81287

回報:

+------------+-----------+-------------+-------+ 
| customerid | productid | productname | ref | 
+------------+-----------+-------------+-------+ 
|  111 |  6577 | ProductA | 111-1 | 
|  111 |  6123 | ProductB | 111-2 | 
|  111 |  1133 | ProductC | 111-3 | 
|  111 |  1133 | ProductC | 111-3 | 
|  222 |  6577 | ProductA | 222-1 | 
|  222 |  6577 | ProductA | 222-1 | 
|  222 |  1578 | ProductL | 222-2 | 
|  333 |  9273 | ProductX | 333-1 | 
+------------+-----------+-------------+-------+ 
3

試試這個

DECLARE @sampledata AS TABLE 
(
CustomerID int,  
ProductID int 
) 

INSERT INTO @sampledata VALUES (111, 6577),(111,6123 ),(111,1133),(111 ,1133) 

SELECT *, 
     CONCAT(s.CustomerID,'-',CAST(dense_rank() over(PARTITION BY s.CustomerID ORDER BY s.ProductID DESC) AS varchar(10))) AS ref 
FROM @sampledata s 
+0

dense_rank是正確的。我剛剛編輯 – TriV

1

你可以使用DENSE_RANK()函數

select *, concat(customerId, '-', dense_rank() over(partition by Customerid order by ProductName)) from #yourCustomer 

你的表:

create table #yourCustomer (CustomerId int, ProductId int, ProductName varchar(20)) 

insert into #yourCustomer (CustomerId, ProductId, ProductName) values 
(111  ,  6577  ,'ProductA') 
,(111  ,  6123  ,'ProductB')  
,(111  ,  1133  ,'ProductC') 
,(111  ,  1133  ,'ProductC')  
,(222  ,  6577  ,'ProductA')  
,(222  ,  6577  ,'ProductA')  
,(222  ,  1578  ,'ProductL')  
,(333  ,  9273  ,'ProductX') 
1

密集的排名答案都非常好,並提供你問什麼了。

但有一個潛在的香蕉皮;如果您在未來的某個時候推出新產品,然後重新運行邏輯,您將得到不同的結果。

如果Ref的格式無關緊要,請考慮連接CustomerIdProductId。例如:111-1變爲111-6577。 222-2變成222-1578。

如果格式很重要,請考慮創建產品表(ProductIdProductNameProductRef)。然後Ref將等於CustomerId + - + ProductRef。例如:

ProductId ProductName  ProductRef 
6577  ProductA  1 
6123  ProductB  2 
1133  ProductC  3 
相關問題