我正在努力通过VB和OleDB更新myTable中的列。
myTable:
myGroup Value1 Value2
A 20 5
B 15 3
A 19 4
A 20 6
C 10 2
B 14 4
C 11 7
我想用value2更新value3列,当value1在组中最高时,其中value2最低。
我有这个:
SELECT myGroup ,MAX(value1), MIN(value2)
FROM myTable
GROUP BY myGroup
我明白了:
myGroup Value1 Value2
A 20 4
B 15 3
C 11 2
但是我需要这个:
myGroup Value1 Value2
A 20 5
B 15 3
C 11 7
我需要类似“ UPDATE mytable SET Value3 = MIN(value2)WHERE MAX(value1)GROUP BY myGroup”之类的东西
myTabel应该像:
myGroup Value1 Value2 Value3
A 20 5 5
B 15 3 3
A 19 4 5
A 20 6 5
C 10 2 7
B 14 4 3
C 11 7 7
请帮忙。
答案 0 :(得分:0)
您可以使用类似:
的查询SELECT t1.myGroup, t1.value1, t2.value2 as value3
FROM myTable t1
LEFT JOIN
(
SELECT myGroup, Value1, MIN(VALUE2) AS value2
FROM myTable
WHERE (myGroup, Value1) in
(
SELECT myGroup , MAX(value1)
FROM myTable
GROUP BY myGroup
)
GROUP BY myGroup, Value1) t2
ON ( t1.myGroup = t2.myGroup );
myGroup Value1 Value3
------- ------ ------
A 20 5
B 15 3
A 19 5
A 20 5
C 10 7
B 14 3
C 11 7
,对于上述SELECT语句,UPDATE语句可能是:
UPDATE myTable t3
SET t3.Value2 =
( SELECT q.value3 FROM
(
SELECT t1.myGroup, t1.value1, t1.value2, t2.value2 as value3
FROM myTable t1
LEFT JOIN
(
SELECT myGroup, Value1, MIN(VALUE2) AS value2
FROM myTable
WHERE (myGroup, Value1) in
(
SELECT myGroup , MAX(value1)
FROM myTable
GROUP BY myGroup
)
GROUP BY myGroup, Value1) t2
ON ( t1.myGroup = t2.myGroup )
) q
WHERE q.myGroup = t3.myGroup
AND q.value1 = t3.value1
AND q.value2 = t3.value2
);
答案 1 :(得分:0)
select t.myGroup as myGroup ,value1,min(t.value2) as min2
from stack t
join (select myGroup,max(value1) as max_value1
from stack
group by myGroup) max1_table
on t.myGroup=max1_table.myGroup and t.value1=max1_table.max_value1
group by myGroup,value1
答案 2 :(得分:0)
一种方法是相关子查询。像这样:
select t.*,
(select t2.value2
from t t2
where t2.mygroup = t.mygroup
order by value1 desc, value2 asc
fetch first 1 row only
) as value3
from t;
这使用ANSI / ISO语法。具体语法可能因您的数据库而异。
这也可以使用标准函数first_value()
来表达:
select t.*,
first_value(value2) over (partition by mygroup order by value1 desc, value2 asc) as value3
from t;