如果你不介意去動態。這種方法確實需要輔助函數來將數據轉換爲EAV結構(實體屬性值)。
Declare @YourTable table (PR int,Inv int,Comm int,Comm1 int,Comm2 int)
Insert Into @YourTable values
(123,1,10, 0, 1),
(234,1,20, 5, 10),
(345,1,40,16, 21),
(098,2,23,65, 76),
(765,2,45,32, 0),
(981,1,65,87, 9),
(981,2,45,32,100)
Select PR=Entity
,Inv
,Col = Concat(B.Attribute,'_',Inv)
,B.Value
Into #Temp
From @YourTable A
Cross Apply (Select * from [dbo].[udf-EAV]((Select A.* for XML RAW)) Where Attribute<>'Inv') B
Declare @SQL varchar(max) = ''
Select @SQL = @SQL+','+QUOTENAME(Col)+'=max(IIF(Col='''+col+''',Value,0))' From (Select Top 100 Percent Inv,Col from #Temp Group By Inv,Col Order by Inv) A
Exec('Select PR'[email protected]+' From #Temp Group By PR Order By Pr')
返回
的UDF
CREATE FUNCTION [dbo].[udf-EAV](@XML xml)
Returns Table
As
Return (
with cteKey(k) as (Select Top 1 xAtt.value('local-name(.)','varchar(100)') From @XML.nodes('/row') As A(xRow) Cross Apply A.xRow.nodes('./@*') As B(xAtt))
Select Entity = xRow.value('@*[1]','varchar(50)')
,Attribute = xAtt.value('local-name(.)','varchar(100)')
,Value = xAtt.value('.','varchar(max)')
From @XML.nodes('/row') As A(xRow)
Cross Apply A.xRow.nodes('./@*') As B(xAtt)
Where xAtt.value('local-name(.)','varchar(100)') Not In (Select k From cteKey)
)
/*
-- Notes: First Field in Query will be the Entity
究竟您正在使用哪個DBMS?完成上述任務的方法各不相同。一個人無法全部回答。 – Susang
sql server 2014 – chanti
你可以在SQL server中使用PIVOT,我認爲你可以通過使用web來完成,所以請嘗試一次。 https://msdn.microsoft.com/en-us/library/ms177410.aspx我認爲你必須首先檢查你的需求,因爲它不完全是可以做到的。 – Susang