SQL Update行包含来自其他平面表的数据

时间:2019-06-25 15:02:56

标签: sql sql-server tsql pivot

我有两个表:资产和价值

资产

unid|name|memory|brand|type|status|processor|supplier|hostname|building|datebought|user
---------------------------------------------------------------------------------------
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|Object1|null|null|null|null|null|null|null|null|null|null
2FFA7056-4C9B-4375-B14F-4A927A55BA0C|Object2|null|null|null|null|null|null|null|null|null|null

assetid|fieldname|textvalue
---------------------------
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|memory|16
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|brand|09e9a777-3899-48ed-a1e8-d50e4469e157
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|type|0261f606-1253-41d3-9b17-4464763bb187
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|status|4dde3e20-da2d-4e1e-a9d4-51039b74e6ca
2FFA7056-4C9B-4375-B14F-4A927A55BA0C|datebought|2017-11-20T23:00:00.000
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|processor|0536f0c2-46f3-4245-b8e8-41e092e03e44
2FFA7056-4C9B-4375-B14F-4A927A55BA0C|type|7380b254-6b40-42b8-9584-a16e6f14409e
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|supplier|c3ee564a-3a46-546f-82e4-7b42f21ec841
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|hostname|object1
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|building|0536f0c2-46f3-9995-b8e8-41e092e03e44
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|datebought|2017-06-14T22:00:00.000
D7930C14-3196-49DA-BAC9-9D03F5FA9E8F|user|ac2d9a93-f09c-5d13-bd78-7e3ba2a749e6
2FFA7056-4C9B-4375-B14F-4A927A55BA0C|brand|09e9a777-3899-48ed-a1e8-d50e4469e157
2FFA7056-4C9B-4375-B14F-4A927A55BA0C|supplier|c3ee564a-3a46-546f-82e4-7b42f21ec841
2FFA7056-4C9B-4375-B14F-4A927A55BA0C|status|4dde3e20-da2d-4e1e-a9d4-51039b74e6ca

如您所见,表Assets的行中有很多空值。空值需要用“值”表中的值填充。

对我来说很难,因为表“值”中的每个值都在单独的行中。因此,需要将“值”中的多行更新为“资产”中单行中的列。

两个表之间的关系是 Assets.unid = Values.assetid

我尝试使用如下所示的数据透视表,但是我仍然不知道如何将数据更新到相应的行。

select "memory", "brand", "type", "status", "processor", "supplier", "hostname", "building", "datebought", "user"
from
(
  select cast(textvalue as varchar(max)) as textvalue, fieldname
  from am_value
) d
pivot
(
  max(textvalue)
  for fieldname in ("memory", "brand", "type", "status", "processor", "supplier", "hostname", "building", "datebought", "user" )
) piv

1 个答案:

答案 0 :(得分:0)

首先,我们将通过以下查询形成透视结果集

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(fieldname) 
                    from Values
                    GROUP BY fieldname 
                    order by 1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT assetid ,' + @cols + ' into #temp from 
             (
                select *
                from values
            ) x
            pivot 
            (
                max(textvalue)
                for COL in (' + @cols + ')
            ) p '

execute(@query);

现在您可以使用temp#中的值更新表