Sql查询关系使用pivot显示动态列

时间:2011-05-02 18:33:39

标签: asp.net sql sql-server

我有一个如下表结构:

表名: 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

现在我想将输出显示为:

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。

1 个答案:

答案 0 :(得分: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'