根据行值将列拆分为多个

时间:2018-02-26 20:16:53

标签: sql sql-server sql-server-2014

尝试根据misc_field_id值将misc_field_value列拆分为多个列。新列名称并不重要。 Column_1,Column_2等。

我找到的所有答案都是根据同一列中的空格或值来拆分列。

编辑:我试过了:

select [10001], [10002], [10003], [10004], [10006] from ( select misc_field_id, misc_field_value from #testtable )d pivot ( max(misc_field_value) for misc_field_id in ([10001], [10002], [10003], [10004], [10006]) )piv;

DEMO

我想我不确定要使用哪种聚合函数?我实际上试图转动大约5000行。

SQL Server 2014

+----+---------------+----------------------+
| ID | misc_field_id |   misc_field_value   |
+----+---------------+----------------------+
|  1 |         10001 | REIA EVENT           |
|  1 |         10002 | Test2 REIA           |
|  1 |         10003 | JOE Black            |
|  1 |         10004 | Test Investing, LLC  |
|  1 |         10006 | NC-1                 |
|  2 |         10001 | BROKER               |
|  2 |         10002 | TOM GOULD            |
|  2 |         10004 | TEST Properties, LLC |
|  2 |         10006 | GA-1                 |
|  3 |         10001 | CLIENT REFERRAL      |
|  3 |         10002 | STEFAN TESTER        |
|  3 |         10004 | SIVA EVANS           |
|  3 |         10006 | GA-1                 |
+----+---------------+----------------------+

Current

我正在寻找的结果如下:

+----+-----------------+---------------+---------------------+----------+
| ID |    Column_1     |   Column_2    |      Column_3       | Column_4 |
+----+-----------------+---------------+---------------------+----------+
|  1 | REIA EVENT      | Test2 REIA    | TEST INVESTING, LLC | NC-1     |
|  2 | BROKER          | TOM GOULD     | TEST Properties LLC | GA-1     |
|  3 | ClIENT REFERRAL | STEFAN TESTER | SIVA EVANS          | GA-1     |
+----+-----------------+---------------+---------------------+----------+

Results

0 个答案:

没有答案