我想编写一个视图脚本。 Catch是我需要使用原始表的一列中的值,并在我的视图中将它们显示在多个列中。有没有人有我可以遵循的示例脚本?例如,我有一个包含20个不同功能的列的表。我需要在视图中有20个不同的列,仅用于功能部分。功能列将包含“皮革座椅”“1/2浴室”
等数据答案 0 :(得分:0)
由于您没有提供DDL或DML,而且我没有时间为您做这件事,我会给您一个通用的''溶液
declare @survey table (Respondent int identity(1,1), Q1 int, Q2 int, Q3 int, Q4 int, Q5 int)
declare @questions table (PK_quID int identity(1,1), quName varchar(255))
declare @answers table (PK_anID int identity(1,1), anName varchar(255))
insert into @questions values ('Do you have a drivers license?')
insert into @questions values ('What best describes your current employment conditions?')
insert into @questions values ('Do you have hair?')
insert into @questions values ('What kind of vehicle do you drive?')
insert into @questions values ('What state are you from?')
insert into @answers values ('yes')
insert into @answers values ('no')
insert into @answers values ('working')
insert into @answers values ('not working')
insert into @answers values ('car')
insert into @answers values ('truck')
insert into @answers values ('suv')
insert into @answers values ('MO')
insert into @answers values ('IL')
insert into @answers values ('TN')
insert into @survey values (1,3,1,5,8)
insert into @survey values (2,4,1,6,8)
insert into @survey values (1,4,1,7,9)
insert into @survey values (2,3,2,6,9)
insert into @survey values (1,3,1,5,10)
select
s.*,
qu.*,
an.*
from
(
select
Respondent,
right(Q,1) as Q,
A
from @survey
unpivot
(
A for Q in (Q1, Q2, Q3, Q4, Q5)
) as u
) s
left outer join @questions qu
on s.Q=qu.PK_quID
left outer join @answers an
on s.a = an.PK_anID
也...
declare @responses table (Respondent int, FK_quID int, FK_anID int)
insert into @responses
(
Respondent,
FK_quID,
FK_anID
)
select
Respondent,
right(Q,1) as Q,
A
from @survey
unpivot
(
A for Q in (Q1, Q2, Q3, Q4, Q5)
) as u
...最后
select
*
from
(
select
Respondent,
quName,
anName
from @responses r
inner join @questions q
on r.FK_quID=q.PK_quID
inner join @answers a
on r.FK_anID=a.PK_anID
) a
pivot
(
count(a.Respondent)
for anName in
(
[yes],
[no],
[working],
[not working],
[car],
[truck],
[suv],
[MO],
[IL],
[TN]
)
) as pvt
有关详情,请参阅以下链接。
http://blogs.lessthandot.com/index.php/datamgmt/dbprogramming/how-to-unpivot-and-pivot/
http://blogs.lessthandot.com/index.php/datamgmt/datadesign/understanding-sql-server-2000-pivot/