T-SQL子ID用于匹配父ID

时间:2016-09-07 10:18:41

标签: sql-server-2012

我有一些孤立的记录,我需要在父记录中进行,但首先我需要基于UserName的后续记录,以获得用户名的第一个实例的id,之后我将更改为父记录,我已经到目前为止得到了这个:

xx.jar "\\some loc\some loc\\"

enter image description here

我希望得到这个: enter image description here

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

我希望从以下位置更新ID列:

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  UserName    FileID
627    TT             626
628    TT             626
629    TT             626
461    WW             460
462    WW             460
463    WW             460
464    WW             460

2 个答案:

答案 0 :(得分:0)

使用Rank

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

答案 1 :(得分: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