表:fieldTable
(只有一列ColumnFileName
)
@fieldTable (ColumnFileName varchar(10))
ColumnFileName: (Values are as below).
f1
f2
f3
f4,
f5
表:ValueTable
(如下9列)
@valuetable(id INT, f1 VARCHAR(100), f2 VARCHAR(100),
f3 VARCHAR(100), f4 VARCHAR(100), f5 VARCHAR(100),
f6 VARCHAR(100), f7 VARCHAR(100), comments VARCHAR(100))
Id f1 f2 f3, f4 f5 f6, f7 comments
----------------------------------------------------------------------
1 Name Id Salary Interest Offer value Salary ''
如何获得如下结果(将表1行的值映射到Table2的列值):
f1,Name,
f2,Id
f3,Salary
f4,Interest
f5,Offer,
f6,value,
f7,Salary,
答案 0 :(得分:2)
我认为这会让你得到你需要的。我首先通过一些适当的插入,所以跟进的人至少可以拥有那些。然后是Basic unpivot和match。
DECLARE @FIELDTABLE TABLE (COLUMNFILENAME VARCHAR(10))
INSERT INTO @FIELDTABLE (COLUMNFILENAME)
VALUES ( 'f1')
,('f2')
,('f3')
,('f4')
,('f5')
,('f6')
,('f7')
DECLARE @VALUETABLE TABLE (Id INT,f1 varchar(100),f2 varchar(100),f3 varchar(100),f4 varchar(100),f5 varchar(100),f6 varchar(100),f7 varchar(100),comments varchar(100))
INSERT INTO @VALUETABLE (Id, f1, f2, f3, f4,f5,f6,f7,comments)
Values (1, 'Name','Id','Salary','Interest','Offer','value','Salary','')
SELECT F.COLUMNFILENAME
,v.Columns
FROM @FIELDTABLE f
inner join
(
SELECT Columns, Columns2
FROM (
SELECT *
from @VALUETABLE
) cp
UNPIVOT
(
Columns FOR Columns2 in (F1,F2,F3, f4,f5,f6,f7)
) as UP
) v
on f.COLUMNFILENAME = v.Columns2