2016-09-07 58 views
1

我有一些孤兒記錄,我需要做成父記錄,但首先我需要基於用戶名的後續記錄有用戶名的第一個實例的ID,然後我會變成一個父記錄,我得到這個至今:T-SQL子ID的匹配父母身份

DECLARE @Test TABLE 

(
ID INT 
,UserName NVARCHAR(30) 
,FileID INT 



) 
INSERT INTO @Test VALUES (1,'TT',1) 
INSERT INTO @Test VALUES (2,'TT',2) 
INSERT INTO @Test VALUES (3,'TT',3) 
INSERT INTO @Test VALUES (4,'WW',4) 
INSERT INTO @Test VALUES (5,'WW',5) 
INSERT INTO @Test VALUES (6,'WW',6) 
INSERT INTO @Test VALUES (7,'WW',7) 
; 
WITH CTE 
AS 
(
    SELECT *,ROW_NUMBER() OVER(Partition by UserName Order by UserName) RN 

    from @Test 
) 
SELECT * 
    FROM CTE 
    ORDER BY Id ASC 

enter image description here

而且我希望得到這樣的: enter image description here

ID UserName FileID RN 
1 TT   1  1 
2 TT   1  2 
3 TT   1  3 
4 WW   4  1 
5 WW   4  2 
6 WW   4  3 
7 WW   4  4 

我希望更新的ID列從:

ID UserName FileID 
627 TT    626 
628 TT    626 
629 TT    626 
461 WW    460 
462 WW    460 
463 WW    460 
464 WW    460 

要這樣:

ID UserName FileID 
627 TT   627 
628 TT   627 
629 TT   627 
461 WW   461 
462 WW   461 
463 WW   461 
464 WW   461 
+0

請輸入預期結果作爲文本 – TheGameiswar

回答

0

使用排名

WITH CTE 
AS 
(
    SELECT ID,USERNAME,RANK() OVER (ORDER BY USERNAME) AS FILEID, 
    ROW_NUMBER() OVER(PARTITION BY USERNAME Order by UserName) RN 

    from @Test 
) 
SELECT * 
    FROM CTE 
    ORDER BY Id ASC 
+0

它的種類我正在嘗試做但不是,我應該說我需要更新FileID從說: – SSMSJ

+0

似乎不工作,當我嘗試與不同的數字看到上面,它保持在我所尋找的。 – SSMSJ

0
DECLARE @Test TABLE 

(
ID INT 
,UserName NVARCHAR(30) 
,FileID INT 



) 
INSERT INTO @Test VALUES (627,'TT',626) 
INSERT INTO @Test VALUES (628,'TT',626) 
INSERT INTO @Test VALUES (629,'TT',626) 
INSERT INTO @Test VALUES (461,'WW',460) 
INSERT INTO @Test VALUES (462,'WW',460) 
INSERT INTO @Test VALUES (463,'WW',460) 
INSERT INTO @Test VALUES (464,'WW',460) 
; 

UPDATE T 
SET FILEID = (SELECT TOP 1 ID FROM @Test TT WHERE T.FILEID = TT.FILEID) 
FROM @Test T; 

SELECT * FROM @Test ORDER BY ID 

結果:

ID UserName FileID 
461  WW  461 
462  WW  461 
463  WW  461 
464  WW  461 
627  TT  627 
628  TT  627 
629  TT  627