sql:基于列中的值生成列
我有一个数据表,比如sql:基于列中的值生成列,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有一个数据表,比如 pr inv comm comm1 comm2 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 98
pr inv comm comm1 comm2
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
我希望结果是一样的
pr comm comm1 comm2 comm comm1 comm2
1 1 1 2 2 2
123 10 0 1 0 0 0
234 20 5 10 0 0 0
345 40 16 21 0 0 0
098 0 0 0 23 65 76
765 0 0 0 45 32 0
981 65 87 9 45 32 100
我的意思是,我必须为每个inv列值生成新列。如果您不介意使用动态。这种方法确实需要一个helper函数来将数据转换为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'+@SQL+' From #Temp Group By PR Order By Pr')
首先取消PIVOT数据,然后进行数据透视,如果有许多库存,最好使用动态SQL生成并运行查询:
SELECT pr,
COALESCE(inv1_comm,0) as inv1_comm,
COALESCE(inv1_comm1,0) as inv1_comm1,
COALESCE(inv1_comm2,0) as inv1_comm2,
COALESCE(inv2_comm,0) as inv2_comm,
COALESCE(inv2_comm1,0) as inv2_comm1,
COALESCE(inv2_comm2,0) as inv2_comm2
FROM (
SELECT pr,
'inv'+CAST(inv as nvarchar(max))+'_'+comms as inv_comms,
[values]
FROM (
SELECT *
FROM YourTable
) as t
UNPIVOT (
[values] FOR comms IN (comm,comm1,comm2)
) as unpv
) as p
PIVOT (
MAX([values]) FOR inv_comms IN (inv1_comm,inv1_comm1,inv1_comm2,inv2_comm,inv2_comm1,inv2_comm2)
) as pvt
输出:
pr inv1_comm inv1_comm1 inv1_comm2 inv2_comm inv2_comm1 inv2_comm2
98 0 0 0 23 65 76
123 10 0 1 0 0 0
234 20 5 10 0 0 0
345 40 16 21 0 0 0
765 0 0 0 45 32 0
981 65 87 9 45 32 100
说明:
首先是取消部分
SELECT pr,
'inv'+CAST(inv as nvarchar(max))+'_'+comms as inv_comms,
[values]
FROM (
SELECT *
FROM YourTable
) as t
UNPIVOT (
[values] FOR comms IN (comm,comm1,comm2)
) as unpv
生成以下内容:
pr inv_comms values
123 inv1_comm 10
123 inv1_comm1 0
123 inv1_comm2 1
234 inv1_comm 20
234 inv1_comm1 5
234 inv1_comm2 10
345 inv1_comm 40
345 inv1_comm1 16
345 inv1_comm2 21
etc...
所以我们从3N列中得到一列中的所有命令
然后,我们使用PIVOT按invs结果集进行展开
需要创建空值-0
按顺序计算参数,并返回最初未计算为NULL的第一个表达式的当前值
您使用的是哪种数据库管理系统?完成上述任务的方法各不相同。sql server 2014您可以在sql server中使用PIVOT,我认为您可以通过使用web来实现这一点,因此请尝试一次。我认为你必须首先审查你的要求,因为这不完全是可以做到的。
pr inv_comms values
123 inv1_comm 10
123 inv1_comm1 0
123 inv1_comm2 1
234 inv1_comm 20
234 inv1_comm1 5
234 inv1_comm2 10
345 inv1_comm 40
345 inv1_comm1 16
345 inv1_comm2 21
etc...