2017-09-25 133 views
-1

以下是表格結構,下面給出了所需的輸出。使用SQL列的數據在SQL中進行數據透視

請按下Run Code Snippet來查看錶格結構。

<html> 
 
    <body> 
 
    <strong>Existing Structure</strong> 
 
    <br> 
 
    <br> 
 
    <table style="width:100%"> 
 
     <tr> 
 
     <th>VoucherID</th> 
 
      <th>ColumnName</th> 
 
      <th>ColumnValue</th> 
 

 
     </tr> 
 
     <tr> 
 
     <td>10</td> 
 
     <td>Buyer Name</td> 
 
     <td>Mr. ABC</td> 
 
     </tr> 
 
     <tr> 
 
     <td>10</td> 
 
     <td>Buyer Address</td> 
 
     <td>Vasant Vihar</td> 
 
     </tr> 
 
     <tr> 
 
     <td>10</td> 
 
     <td>Buyer City</td> 
 
     <td>New Delhi</td> 
 
     </tr> 
 
     <tr> 
 
     <td>10</td> 
 
     <td>Buyer Email</td> 
 
     <td>[email protected]</td> 
 
     </tr> 
 
    </table> 
 
<br> 
 
<strong>I want output as follow:-</strong> 
 
<br> 
 
<br> 
 
     <table style="width:100%"> 
 
      <tr> 
 
      <th>VoucherID</th> 
 
       <th>Buyer Name</th> 
 
       <th>BuyerAddress</th> 
 
       <th>BuyerCity</th> 
 
       <th>BuyerEmail</th> 
 

 
      </tr> 
 
      <tr> 
 
      <td>10</td> 
 
      <td>Mr. ABC</td> 
 
      <td>Vasant Vihar</td> 
 
      <td>New Delhi</td> 
 
      <td>[email protected]</td> 
 
      </tr> 
 
     </table> 
 
     </body> 
 
     </html>

嗨, 我使用SQL Server 2016 創建從 「dbo.TransactionDetails.ColumnName」 動態列和 「dbo.TransactionDetails.ColumnValue」 取值,其中TransactionDetail是表名和「ColumnName」列包含要動態創建的列的名稱,該列中的值將取自「ColumnValue」。 請幫助獲取所需的輸出。如果有可能徹底擺動或任何其他方式。引導我通過。

我所做的是添加多個事務處理細節表,並通過使用稱爲HARDCODING的「where」來獲得所需的輸出。但需要通過旋轉或任何其他方式做到這一點

+0

請編輯您的問題,並刪除所有HTML標籤。你的問題看起來像一個HTML而不是數據樣本。 – FLICKER

回答

0

試試這個

create table #Table1 
(VoucherID int, ColumnName varchar(100), ColumnValue varchar(255)) 

insert into #Table1 
values (10,'Buyer Name','Mr. ABC') 
, (10,'Buyer Address','Vasant Vihar') 
, (10,'Buyer City','New Delhi') 
, (10,'Buyer Email','[email protected]') 



select * from #Table1 

Select * from 
(
    Select VoucherID,ColumnName,ColumnValue from #Table1 
) as src 
pivot 
(
    MAX(ColumnValue) 
    FOR ColumnName IN([Buyer Name],[Buyer Address],[Buyer City],[Buyer Email]) 
)as pvt 

--Drop table #Table1 

enter image description here

+0

謝謝你,如果可以的話,請給出答案。 –