是否有一种简单的方法(T-)SQL将行转换为像这样的列?

时间:2016-02-23 17:48:00

标签: sql asp.net sql-server tsql database-design

所以,让我说我有3个表,比如

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<table>

<tr>

<td>

<dl class="select">
    <dt><span id="vegetables"></span></dt>
    <dd>
        <ul>
            <li><a href="#">&nbsp;</a></li>
            <li><a href="#">Carrots</a></li>
            <li><a href="#">Celery</a></li>
            <li><a href="#">Brocoli</a></li>
        </ul>
    </dd>
</dl>

</td>

<td>
<dl class="select">
    <dt><span id="fruits"></span></dt>
    <dd>
        <ul>
            <li><a href="#">&nbsp;</a></li>
            <li><a href="#">Apples</a></li>
            <li><a href="#">Oranges</a></li>
            <li><a href="#">Bananas</a></li>
        </ul>
    </dd>
</dl>

</td>
</tr>
</table>

有没有办法从这个像

这样的表创建
       Questions 
========================
 id |     qtext 
========================
 1  | "What is 3 x 23?"
------------------------
 2  | "Your age?"

      Registrants
========================
 id |    name 
========================
 1  | "Jason" 
------------------------
 2  | "Subhasish"

               Answers
======================================
 registrant_id | question_id  | val 
======================================
      1        |       1      |  69
--------------------------------------
      2        |       2      |  45
--------------------------------------
      1        |       2      |  26

2 个答案:

答案 0 :(得分:2)

是的!在这里(请查看拼写错误的列名称):

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.qtext) 
            FROM Questions c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query = 'SELECT Name, ' + @cols + ' from 
            (
                select r.name, a.val,q.qtext from
                registrants r               
                inner join answers a
                on r.id = a.registrant_id
                inner join questions q
                on q.id = a.question_id
           ) x
            pivot 
            (
                 max(val)
                for qtext in (' + @cols + ')
            ) p '


execute(@query)

答案 1 :(得分:2)

我总是喜欢这样做:

select
   R.name as Name, 
   A1.val as [What is 3 x 23?],
   A2.val as [Your age?]
from Registrants R
left join Answers A1 on R.id = A1.registrant_id and A1.question_id = 1
left join Answers A2 on R.id = A2.registrant_id and A2.question_id = 2