SQL Server 2012: 我有表A(Cust_ID INT,P_ID UNIQUE INT,P_Name,Match_ID,Issue_Date)
Cust_ID P_ID P_Name Match_ID Issue_Date
1 214 J5 1 2009-01-01
1 478 U3 1 2013-05-02
1 258 21 2 2003-04-05
1 369 65 2 2013-05-02
2 235 69 1 2011-05-09
2 897 36 1 2013-05-02
现在基本上,行2,3和6从第1,3和5行填充,因此它们具有相同的Match_Id,2,4,6具有今天的日期。我想创建一个映射表,如下所示:
我有一个表A(CustID,P_ID,P_Name,New_P_ID,New_P_Name)
Cust_ID P_ID P_Name New_P_ID New_P_Name
1 214 J5 478 U3
1 258 21 369 65
2 235 69 897 36
请给我一个查询,我尝试过很多东西,但听起来很简单。 非常感谢。
答案 0 :(得分:0)
INSERT INTO #B (Cust_ID , P_ID , P_Name, Match_ID )
SELECT cust_ID , P_ID, P_Name, Match_ID from #A WHERE Issue_Date < GETDATE()
UPDATE #B
SET New_P_ID = NEW
FROM ( Select New_P_ID, new = #A.P_Id from #B INNER JOIN #A ON #A.Cust_ID = #B.Cust_ID AND #A.Match_ID = #B.Match_ID AND #A.P_ID <> #B.P_ID ) #B
UPDATE #B
SET New_P_Name = NEW
FROM ( Select New_P_Name, new = #A.P_Name from #B INNER JOIN #A ON #A.Cust_ID = #B.Cust_ID AND #A.Match_ID = #B.Match_ID AND #A.P_ID <> #B.P_ID ) #B