获取行值作为列头
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取行值作为列头相关的知识,希望对你有一定的参考价值。
我有两张表,如下图所示,我想把这两张表连接起来,需要把第二张表的列值设置为列头,如下图所示。我想把这两个表连接起来,需要把第二个表的列值设置为列头,如下图所示。我怎样才能实现这个目标?
表1
ID NAME
---------------
1 AAA
2 BBB
表2
ID QUESTION ANSWER
----------------------------------
1 Q1 YES
1 Q2 NO
1 Q3 YES
1 Q4 NO
1 Q5 YES
2 Q1 YES
2 Q2 YES
2 Q3 YES
2 Q4 YES
2 Q5 YES
输出表应该是
ID NAME Q1 Q2 Q3 Q4 Q5
----------------------------------------------------
1 AAA YES NO YES NO YES
2 BBB YES YES YES YES YES
答案
你可以使用动态透视法,如下图所示------。
DECLARE @cols AS NVARCHAR(MAX),
@sqlCommand AS NVARCHAR(MAX);
SELECT @cols =
STUFF((SELECT ( '],[' + A.QUESTION)
FROM (SELECT DISTINCT QUESTION FROM table2) A
ORDER BY A.QUESTION
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')+']'
FROM table2
SET @sqlCommand=
N'SELECT [ID],NAME,'+SUBSTRING(@cols,2,LEN(@cols))+'
FROM
(
SELECT A.ID,A.NAME, B.QUESTION, B.ANSWER
FROM table1 A
INNER JOIN table2 B ON A.ID = B.ID
) AS P
PIVOT
(
MAX(ANSWER)
FOR QUESTION IN('+SUBSTRING(@cols,2,LEN(@cols))+')
) PVT'
--PRINT @sqlCommand
EXEC (@sqlCommand)
另一答案
你必须使用Pivot来写这个查询。
Sample Data:
DECLARE @Table1 TABLE( id int, name nvarchar(10));
DECLARE @Table2 TABLE( id int, Question nvarchar(10),Answer nvarchar(10))
insert into @Table1 (id,[name])values(1,'AAA')
insert into @Table1 (id,[name])values(2,'BBB')
insert into @Table2 (id,Question,Answer)values(1,'Q1','YES')
insert into @Table2 (id,Question,Answer)values(1,'Q2','NO')
insert into @Table2 (id,Question,Answer)values(1,'Q3','YES')
insert into @Table2 (id,Question,Answer)values(1,'Q4','NO')
insert into @Table2 (id,Question,Answer)values(1,'Q5','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q1','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q2','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q3','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q4','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q5','YES')
select * from @Table1 t1
inner join (
select * from(
select
t2.id
,t2.Question
,t2.Answer
from @Table2 t2
)temp
pivot
(
MAX(Answer)
for question in ([Q1],[Q2],[Q3],[Q4],[Q5])
) as PivotTable
)TemporaryTable on t1.id=TemporaryTable.id
如果你的 "问题 "是动态的,你可以这么写
Declare @cols nvarchar(MAX);
Declare @query nvarchar(MAX);
set @cols=( select STRING_AGG('['+Question+']',',') from @Table2);
set @query='
select * from @Table1 t1
inner join (
select * from(
select
t2.id
,t2.Question
,t2.Answer
from @Table2 t2
)temp
pivot
(
MAX(Answer)
for question in ('+@cols+')
) as PivotTable
)TemporaryTable on t1.id=TemporaryTable.id
'
exec sp_executesql @query
另一答案
这不是你通常要在你的展示层做的事情吗? 报表工具就是为这个而生的。
以上是关于获取行值作为列头的主要内容,如果未能解决你的问题,请参考以下文章
尝试使用Javascript从gridview获取复选框选中的行值