2017-01-04 26 views
0

输入数据SQL服务器 - 透视 - 行入列的多个VARCHAR列

需要转动ID数据。和所需的输出如下:

输出所需

需要适当的解决方案,这将给有效输出。

添加文本作为替代图像:

输入数据:

+---+----+-------+------+------ +---------+-------+ 

|ID |Q_NO| SUB_CD|PR_TX |C_TX |AD_DTL_TX| B_NM | 

+---+----+-------+------+------ +---------+-------+ 
|111| 1| A |asd |sdf |qwerwet |qqwe | 
|111| 1| B |ger |sdt |uutty | ttt | 
|112| 1| B |yut |www |yyjy  | y  | 
|114| 1| A |atd |stf |qwwet |qe  | 
|114| 1| B |atw |rf  |qwet  |qwp | 
|114| 2| A |aq  |yf  |qyet  |qoe | 
|117| 1| A |aee |yrr |qyet  |qoe | 
|117| 2| A |tq  |uf  |et  |oe  | 
+---+----+-------+------+------ +---------+-------+ 

所需的输出:

+---+-----------+---------+---------+-----------+------------+---------+-----------+-------------+--------------+-----------+------------+-------+----------+---------+-------------+-----------+-----------+----------+ 

|ID |Q_NO_1A |SUB_CD_1A| PR_TX_1A|C_TX_1A |AD_DTL_TX_1A| B_NM_1A| Q_NO_1B| SUB_CD_1B| PR_TX_1B |C_TX_1B |AD_DTL_TX_1B|B_NM_1B| Q_NO_2A |SUB_CD_2A| PR_TX_2A |C_TX_2A |AD_DTL_TX_2A| B_NM_2A| 
+---+-----------+---------+---------+-----------+------------+---------+-----------+-------------+--------------+-----------+------------+-------+----------+---------+-------------+-----------+-----------+----------+ 
|111| yes  | yes | asd | sdf |  qwerwet|  qqwe|  yes|   yes|  ger |  sdt |  uutty | ttt | null | null | null  |  null |  null | null | 
|112| null | null | null | null |  null |null  |yes  |  yes |   yut |  www |  yyj |y  | null | null | null  |null  |  null |null  | 
|114| yes  | yes | atd | stf  |  qwwet | qe | yes |  yes |  atw  |  rf |  qwe | qwp | yes |  yes |  aq  |  yf | qyet |qoe  | 
|117| yes  | yes | aee |yrr  | qyet  |  qoe | null | null  |  null | null | null | null| yes | yes |  tq  |  uf |  et | oe  | 
+---+-----------+---------+---------+-----------+------------+---------+-----------+-------------+--------------+-----------+------------+-------+----------+---------+-------------+-----------+-----------+----------+ 

+1

大多数我们希望样本数据以及格式化文本,而不是图片。 – jarlh

+0

请格式化您的**必需输出**。 – McNets

回答

2

一对夫妇工会和枢转的。

select * 
from 
(
    select id, concat('Q_NO_', q_no, sub_cd) as title, 'yes' as value from YourTable 
    union all 
    select id, concat('SUB_CD_', q_no, sub_cd) as title, 'yes' as value from YourTable 
    union all 
    select id, concat('PR_TX_', q_no, sub_cd) as title, pr_tx as value from YourTable 
    union all 
    select id, concat('C_TX_', q_no, sub_cd) as title, c_tx as value from YourTable 
    union all 
    select id, concat('AD_DTL_', q_no, sub_cd) as title, ad_dtl_tx as value from YourTable 
    union all 
    select id, concat('B_NM_', q_no, sub_cd) as title, b_nm as value from YourTable 
) q 
pivot (max(value) FOR title IN (
    [Q_NO_1A],[SUB_CD_1A],[PR_TX_1A],[C_TX_1A],[AD_DTL_1A],[B_NM_1A], 
    [Q_NO_1B],[SUB_CD_1B],[PR_TX_1B],[C_TX_1B],[AD_DTL_1B],[B_NM_1B], 
    [Q_NO_2A],[SUB_CD_2A],[PR_TX_2A],[C_TX_2A],[AD_DTL_2A],[B_NM_2A] 
) 
) pvt;