您好我需要能够连接两个表并返回第二个表 作为第一个表的列。我需要创造 (从属名,从属姓和依赖关系) 基于最大数量depid(可以是动态的)。
提前谢谢
表1
+-------------+-------------+------------+
| employeeid | first name | last name |
+-------------+-------------+------------+
| 1 | bill | johnson |
| 2 | matt | smith |
| 3 | katy | lewis |
+-------------+-------------+------------+
表2
+-------------------------------------------------------------------+
| employeeid |dependent id | First Name | Last Name | Relationship |
+-------------------------------------------------------------------+
| 1 1 mary johnson spouse |
| 1 2 aaron johnson child |
| 2 1 eric smith child |
+-------------------------------------------------------------------+
预期产出
+------------+------------+-----------+----------------------+---------------------+------------------------+----------------------+---------------------+------------------------+
| employeeid | first name | last name | dependent first name | dependent last name | dependent relationship | dependent first name | dependent last name | dependent relationship |
+------------+------------+-----------+----------------------+---------------------+------------------------+----------------------+---------------------+------------------------+
| 1 | bill | johnson | mary | johnson | spouse | aaron | johnson | child |
| 2 | matt | smith | eric | smith | child | | | |
| 3 | katty | lewis | | | | | | |
+------------+------------+-----------+----------------------+---------------------+------------------------+----------------------+---------------------+------------------------+
答案 0 :(得分:0)
你可以用动态SQL&下面的XML Path示例
- 表1
CREATE TABLE#TMP1(EMP_ID INT,NAME Char(10)) 插入#TMP1 VALUES(1,'One') 插入#TMP1值(2,'TWO') 插入#TMP1 VALUES(3,'Three')
- 表2
CREATE TABLE#TMP2(EMP_ID INT,DP_ID INT,FNAME Char(10),Rel Char(10)) 插入#TMP2 VALUES(1,1,'Spouse One','Spouse') 插入#TMP2 VALUES(1,2,'Child One','Child') 插入#TMP2 VALUES(2,1,'Child TWO','Child')
宣布@CNT Int ,@ Ctr int = 0 ,@ SQL VarChar(MAX)
- 获取最大相关ID
从#TMP2
中选择@CNT = MAX(DP_ID)- 用于验证 选择@CNT
- 构建动态SQL以获取数据集
SET @SQL ='SELECT Emp_ID'
而@Ctr< @CNT
开始
Set @Ctr = @Ctr+1
SET @SQL = @SQL + ', ( SELECT FName+'+''''+''''+' FROM #TMP2 Where #TMP1.EMP_ID = #TMP2.EMP_ID and #TMP2.DP_ID = '+Convert(VarChar(2),@Ctr)+' For XML Path ('+''''+''''+') ) as FName'+Convert(VarChar(2),@Ctr)
SET @SQL = @SQL + ', ( SELECT Rel+'+''''+''''+' FROM #TMP2 Where #TMP1.EMP_ID = #TMP2.EMP_ID and #TMP2.DP_ID = '+Convert(VarChar(2),@Ctr)+' FOR XML Path ('+''''+''''+') ) as Rel'+Convert(VarChar(2),@Ctr)
结束
SET @SQL = @ SQL +'FROM#TMP1'
- 用于验证打印动态SQL
选择@SQL
- 执行动态SQL
EXEC(@SQL)