【问题标题】:Pivot and merge columns in a SQL Server stored procedure在 SQL Server 存储过程中透视和合并列
【发布时间】:2014-07-03 17:32:03
【问题描述】:

我有一个包含以下列的表格

Col1(bigint) | Col2(datetime)| Col3(nvarchar(100))| Col4(xml)

第 4 列是一个 xml,如下所示,它可以包含任意数量的字段

<Fields>
  <Field1>10</Field1>
  <Field2>11</Field2>
  <Field3>10</Field3>
  <Field4>11</Field4>
</Fields>

我需要从表中查询多行。我正在创建一个获取 2 个参数的存储过程

参数1:@queryxml的类型)

<Rowset> 
   <Row> 
     <Col1>20140510123205321</Col1> 
     <Col2>2014-05-14T13:01:03.1426856+05:30</Col2> 
     <Col3>Source1</Col3> 
   </Row> 
   <Row> 
     <Col1>20140510123205322</Col1> 
     <Col2>2014-05-14T13:01:03.1426856+05:30</Col2> 
     <Col3>Source2</Col3> 
   </Row> 
</Rowset> 

参数2:@Fields(逗号分隔的字符串类型)

Field1,Field2,Field3,Field4

我期待以下格式的输出

Col1      |   Col2   |  Col3 | Field1 | Field2 | Field3 | Field4 
-----------------------------------------------------------------
2014051092|2014-05-14|Source1|   10   |   21   |  12    |   43 
2014051093|2014-05-14|Source1|   11   |   22   |  23    |   53 

我已经根据存储过程中的第一个参数创建了一个表。

INSERT INTO #TempPricing                     
 (                                                                              
    Col1,
    Col2,
    Col3                                                  
 )                                                                              
SELECT                                                                               
    Col1,
    Col2,
    Col3                               
    FROM OPENXML(@handle, '/Rowset/Row', 2)                                                                                 
 WITH                                                                               
 (                                                         
    Col1 bigint,
    Col2 datetime,
    Col3 varchar(50)      
 )  

拆分后如何旋转第二个参数,将其与上表合并并获取数据?

编辑 输出也可以是以下格式

Col1      |   Col2   |  Col3 | Fields 
--------------------------------------
2014051092|2014-05-14|Source1|<Fields><Field1>10</Field1><Field1>11</Field1></Fields>
2014051093|2014-05-14|Source1|<Fields><Field1>20</Field1><Field1>21</Field1></Fields>

所以上述任何格式都可以工作

【问题讨论】:

标签: sql sql-server tsql sql-server-2005 stored-procedures


【解决方案1】:

让我们试试下面的脚本,它可能会对你有所帮助。

declare @String varchar(max), @Result varchar(max)

select @String= COALESCE(@String+',', '')+ QUOTENAME(Col1) 
FROM (
select distinct Col1 from TableA A Inner Join dbo.Tab C VS on A.AttributeID =VS.AttributeId)AS B
set @Result ='
with pivotData AS
(
select distinct P.Col1, PA.col1,A.Col1,PA.col2 from Tab3 PA join Attribute A
on A.AttributeID=PA.AttributeID join Product P on P.ProductId=PA.ProductId
)
select Col1, Col2,
'+@String+' from pivotData
pivot(
Max(col2) for
Col1in('+@String+')
)as PR order by col3 desc'

exec (@Result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多