2011-05-02 26 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