SQL将行转换为N行(基于列值)

时间:2016-03-10 13:06:28

标签: sql sql-server

我有一个类似于下面示例的表,并尝试UNPIVOT表每行只保留一个链接,并添加一个基于UNPIVOT的信息列。

我设法部分达到我想要的结果,但最后一部分需要一些帮助。到目前为止,我有这个查询:

SELECT Theme,  Area, URL
FROM
(
  SELECT Theme, Area, URL_1, URL_2, URL_3 
  FROM table

) AS a
UNPIVOT 
(
  URL FOR URLs IN (URL_1, URL_2, Url_3)
) AS b WHERE URL <> '';

如何使用基于URL的信息添加此额外列?

提前谢谢。

<h1>Have</h1>
<table border="1" cellpadding="1" cellspacing="2">
  <tr>
    <th>Theme</th>
    <th>Area</th>

    <th>URL_1</th>
    <th>URL_2</th>
    <th>URL_3</th>
  </tr>
  <tr>
    <td>A</td>
    <td>B</td>

    <td>Some URL</td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>A</td>
    <td>C</td>

    <td>Some URL</td>
    <td>Some URL</td>
    <td></td>
  </tr>

  <tr>
    <td>D</td>
    <td>B</td>

    <td>Some URL</td>
    <td>Some URL</td>
    <td></td>
  </tr>

  <tr>
    <td>B</td>
    <td>D</td>

    <td>Some URL</td>
    <td>Some URL</td>
    <td>Some URL</td>
  </tr>
</table>

<h1>Would like</h1>
<table border="1" cellpadding="1" cellspacing="2">
  <tr>
    <th>Theme</th>
    <th>Area</th>

    <th>URL</th>
    <th>Type</th>
  </tr>
  <tr>
    <td>A</td>
    <td>B</td>

    <td>Some URL</td>
    <td>1</td>

  </tr>
  <tr>
    <td>A</td>
    <td>C</td>

    <td>Some URL</td>
    <td>1</td>

  </tr>
  <tr>
    <td>A</td>
    <td>C</td>


    <td>Some URL</td>
    <td>2</td>
  </tr>

  <tr>
    <td>D</td>
    <td>B</td>

    <td>Some URL</td>
    <td>1</td>

  </tr>
  <tr>
    <td>D</td>
    <td>B</td>


    <td>Some URL</td>
    <td>2</td>
  </tr>




  <tr>
    <td>B</td>
    <td>D</td>

    <td>Some URL</td>
    <td>1</td>

  </tr>
  <tr>
    <td>B</td>
    <td>D</td>


    <td>Some URL</td>
    <td>2</td>
  </tr>
  <tr>
    <td>B</td>
    <td>D</td>


    <td>Some URL</td>
    <td>3</td>
  </tr>


</table>

<h1>What I got so far</h1>
<table border="1" cellpadding="1" cellspacing="2">
  <tr>
    <th>Theme</th>
    <th>Area</th>

    <th>URL</th>
  </tr>
  <tr>
    <td>A</td>
    <td>B</td>

    <td>Some URL</td>

  </tr>


  <tr>
    <td>A</td>
    <td>C</td>

    <td>Some URL</td>

  </tr>
  <tr>
    <td>A</td>
    <td>C</td>


    <td>Some URL</td>

  </tr>


  <tr>
    <td>D</td>
    <td>B</td>

    <td>Some URL</td>


  </tr>
  <tr>
    <td>D</td>
    <td>B</td>


    <td>Some URL</td>

  </tr>




  <tr>
    <td>B</td>
    <td>D</td>

    <td>Some URL</td>


  </tr>
  <tr>
    <td>B</td>
    <td>D</td>


    <td>Some URL</td>

  </tr>
  <tr>
    <td>B</td>
    <td>D</td>


    <td>Some URL</td>

  </tr>


</table>

1 个答案:

答案 0 :(得分:1)

简短回答:

SELECT Theme,  Area, UrlKind, URL
FROM
(
  SELECT Theme, Area, URL_1, URL_2, URL_3 
  FROM table

) AS a
UNPIVOT 
(
  URL FOR UrlKind IN (URL_1, URL_2, Url_3)
) AS b WHERE URL <> '';

因此,该列的名称由FOR ...部分的unpivot定义。