使用數據透視表作為子查詢的結果集 - MSSQL

[英]Resultset with pivot table as sub query - MSSQL


I have two tables with following structure. enter image description here

我有兩個表格,結構如下。

and

enter image description here

and I want results like this from one query.

我想從一個查詢中得到這樣的結果。

CUSTOMER_CODE | CUSTOMER_NAME | LINE 1 |LINE 2 | LINE 3

CUSTOMER_CODE | CUSTOMER_NAME |第1行|第2行|第3行

we have to make first table as pivot, but how not sure. Please advise. Thanks

我們必須把第一個表作為樞軸,但是如何不確定。請指教。謝謝

1 个解决方案

#1


0  

Here is a dynamic conditional aggregation There were no table names, so TABLE1 relates to Image1

這是一個動態條件聚合沒有表名,所以TABLE1與Image1有關

Declare @SQL varchar(max)=''
Select @SQL = @SQL+',[Line '+cast([Line#] as varchar(25))+']=max(case when [Line#]='+cast([Line#] as varchar(25))+' then EMail else '''' end)'
 From (Select Distinct [Line#] from Table1) A
 Order By [Line#] 

Select @SQL='
Select A.Customer_Code
      ,B.Customer_Branch_Name'+@SQL+' 
 From  Table1 A 
 Join  Table2 B 
   on  A.Customer_Code=B.Customer_Branch 
 Group By A.Customer_Code,B.Customer_Branch_Name'
Exec(@SQL)

Returns

enter image description here


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/11/20/1adcbe677a8b65a16e12a81800e03c3b.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com