假设我有一个
表A
(A_pkey,B_pkey,A_type,A_value)
和表B
(B_pkey, B_minValueForTypeX,B_maxValueTypeX,B_minValueForTypeY,B_maxValuForeTypeY,B_minValueForTypeZ,B_maxValueForTypeZ)
具有以下值:
1,1,'X',100
2,1,'X',1000
3,1,'X',300
4,1,'Y',500
5,1,'Y',200
6,1,'Z',300
7,2,'X',100
8,2,'X',200
9,2,'X',300
10,2,'Y',100
11,2,'Y',2000
1,NULL,NULL,NULL,NULL,NULL,NULL
2,NULL,NULL,NULL,NULL,NULL,NULL
是否可以在一个查询中更新B以便
B_minValueForTypeX= min(A_value) from A where A_type='X' (with A.B_pkey=B.B_pkey)
B_maxValueForTypeX= max(A_value) from A where A_type='X' (with A.B_pkey=B.B_pkey)
B_minValueForTypeY= min(A_value) from A where A_type='Y' (with A.B_pkey=B.B_pkey)
依旧......
这样表B就像那样
1,100,1000,200,500,300,300
2,100,300,100,2000,0,0
我确信它可以完成,但没有弄清楚如何。
有人可以帮我吗?
感谢您的帮助
答案 0 :(得分:0)
WITH cte (key, value1, value2, value3, value4...)
(
SELECT B_pkey,
MIN(CASE WHEN A_type = 'x' then A_value else null end),
max(CASE WHEN A_type = 'x' then A_value else null end),
MIN(CASE WHEN A_type = 'y' then A_value else null end),
max(CASE WHEN A_type = 'y' then value3 else null end),
.
.
.
FROM A
GROUP BY B_pkey
)
update b
set B_minValueForTypeX = cte.value1,
B_maxValueTypeX = cte.value2,
B_minValueForTypeY = cte.value3,
B_maxValuForeTypeY = cte.value4,
.
.
.
from b
inner join cte on
b.B_pkey= cte.B_pkey