开发者

Sql query relations display dynamic columns using pivot

I have a table structure like below:

Table name: questionsTable and the date is look like

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

Another Table name: tbl_Answer and the data is look like

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

Now I want to display my output to look like this:

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

Here I want to display question lable dynamic because here s开发者_C百科ample I have taken 3 qid.


Not exactly what you asked for, but it possibly a better solution :

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

which results in:

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

Setup:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜