我有两张桌子
table1
productName category S_Id value
p1 cat1 1 year
p1 cat1 2 test1
p1 cat1 3 test2
table2
S_Id specificatio
1 year
2 test1
3 test2
我需要绑定网格视图,如
productName category year test1 test2
p1 cat1 1 2 3
我试过
select P.productName,P.category,S.specification from table1 P inner join table2 S on(P.S_Id=S.S_Id)
但显示结果如
productName category specification
p1 cat1 year
p1 cat1 test1
p1 cat1 test2
任何人都可以帮助如何实现这一点。谢谢提前
答案 0 :(得分:3)
试试这个:
create table table1
(
productname varchar(10),
category varchar(10),
S_Id int,
value varchar(10)
);
insert into table1 values('p1','cat1',1,'year');
insert into table1 values('p1','cat1',2,'test1');
insert into table1 values('p1','cat1',3,'test2');
create table table2
(
S_Id int,
specification varchar(10)
);
insert into table2 values(1,'year');
insert into table2 values(2,'test1');
insert into table2 values(3,'test2');
/ 预期结果的动态查询 /
Declare @cols varchar(max);
Declare @sql varchar(max);
select @cols = STUFF((SELECT ',' + QUOTENAME(specification)
from table2
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
SET @SQL = N'select productName,category,'+@cols+'
from
(
select t1.productname,t1.category,t2.S_ID,t2.Specification
from table1 t1
inner join
table2 t2
on t1.S_ID = t2.S_ID
)x
pivot
(
MAX(S_Id)
FOR SPECIFICATION IN ('+@cols+')
) PV';
EXEC(@SQL);
<强>结果强>:
productName category year test1 test2
------------------------------------------
p1 cat1 1 2 3
答案 1 :(得分:1)
试试这个,
SELECT * FROM (SELECT P.productName,
P.category,
S.specification,P.S_Id
FROM #table1 P
INNER JOIN #table2 S ON( P.S_Id = S.S_Id ) )A
PIVOT (MAX(A.S_Id) FOR A.SPECIFICATION IN ([year],[test1],[test2])) PV