我有2个具有共同列ID的表
Table A:
ID value1 value2 value3
------------------------------------
1 0 0 0
Table B:
ID value_type value
--------------------------------------
1 value1 0.01
2 value2 0.02
3 value3 0.03
我想使用表b的值更新表A的值,
Final Output :
ID value1 value2 value3
-----------------------------------------
1 0.01 0.02 0.03
任何人都可以向我展示如何编写查询并如上所述获取结果,非常感谢!我尝试加入,枢纽。全部都没有结果。
答案 0 :(得分:1)
一种快速(但不可扩展)的解决方案是将update语句与有条件农耕的派生表结合使用:
UPDATE T
SET value1 = v1,
value2 = v2,
value3 = v3
FROM TableA T
JOIN
(
SELECT 1 As ID
MAX(CASE WHEN value_type = 'value1' THEN value END) As v1,
MAX(CASE WHEN value_type = 'value2' THEN value END) As v2,
MAX(CASE WHEN value_type = 'value3' THEN value END) As v3
FROM TableB
) V
ON T.ID = V.ID
答案 1 :(得分:0)
使用枢轴,我们可以做到
由于iam将数据存储到一个表中,之后只有iam doinn更新
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.value_type)
FROM #b c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT rn as id , ' + (@cols) + ' into dynamictable from
(
select *,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID ) AS RN
from #b
) x
pivot
(
MAX(VALUEE)
for VALUE_TYPE in (' + @cols + ')
) p
'
exec(@query)
UPDATE T
SET T.value1 = V.value1,
T.value2 = V.value2,
T.value3 = V.value3
FROM #a T
JOIN
(SELECT id ,MAX(VALUE1)VALUE1 , MAX(VALUE2)VALUE2, MAX(VALUE3)VALUE3
FROM dynamictable
GROUP BY id
) V
ON T.ID = V.ID