2011-05-02 76 views
1

动态列我有一个表结构如下图所示:SQL查询的关系显示使用数据透视

表名:questionsTable和日期看起来像

qid  qName 
    1  Enter your licence number. 
    2  What is your favaorite sport. 
    3  Enter your attendee name 

另一个表名:tbl_Answer和数据看起来像

qid attendeeid Answer 
1  2349   45645645 
2  2349   Cricket 
3  2350   James 
2  2350   Chess 
1  2350   858585 

现在我想显示我的输出为低OK这样:

attendeeid questionlable   answer  questionlable     answer questionlable   answer  
    2349  Enteryourlicencenumber 45645645 Whatisyourfavaoritesport  Cricket 
    2350  Enteryourlicencenumber 858585  What is your favaorite sport hockey Enteryourattendeename James 

在这里,我想显示问题标签动态,因为这里的示例我已采取3 qid。

+2

如果您发布的代码,XML或数据样本,请**在文本编辑器中高亮显示这些行,然后单击编辑器工具栏上的“代码示例”按钮(“{}”)以很好地形成在和语法突出它! – 2011-05-02 19:25:15

回答

0

不是你问什么了,但它可能是一个更好的解决方案:

select attendeeid, [1] as [Enteryourlicencenumber], [2] as [Whatisyourfavaoritesport], [3] as [Enteryourattendeename] 
from 
    (select * from tbl_Answer) as p 
pivot 
    (min(Answer) for qid in ([1], [2], [3])) as pvt 

导致:

attendeeid Enteryourlicencenumber Whatisyourfavaoritesport Enteryourattendeename 
---------- ---------------------- ------------------------ --------------------- 
2349  45645645    Cricket     NULL 
2350  858585     Chess      James 

设置:

create table questionsTable 
(
    qid int primary key 
    , qName varchar(max) not null 
) 

create table tbl_Answer 
(
    qid int not null 
    , attendeeid int not null 
    , Answer nvarchar(max) not null 
) 

insert into questionsTable 
select 1, 'Enter your licence number.' 
union all 
select 2, 'What is your favaorite sport.' 
union all 
select 3, 'Enter your attendee name' 


insert into tbl_Answer 
select 1, 2349, '45645645' 
union all 
select 2, 2349, 'Cricket' 
union all 
select 3, 2350, 'James' 
union all 
select 2, 2350, 'Chess' 
union all 
select 1, 2350, '858585' 
+0

谢谢您的回复,但在我的查询中,我想显示的问题显示在下方可疑的位置显示Enteryourlicencenumber并在此行旁边我想显示答案labl显示与会者可疑答案可疑答案可疑答案 2350 Enteryourlicencentumber 858585什么是你的favaorite体育曲棍球Enteryourattendeename詹姆斯 – Sree 2011-05-02 21:04:02