0

假设我有一个

表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

我确定可以做到,但不知道怎么做。

有人可以帮我吗?

谢谢你的帮助

4

1 回答 1

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
于 2013-06-21T15:09:27.453 回答