Name type Age
-------------------------------
Vijay 1 23
Kumar 2 26
Anand 3 29
Raju 2 23
Babu 1 21
Muthu 3 27
--------------------------------------
编写一个查询,将每种类型的最大年龄人名更新为“HIGH”。
还请告诉我,为什么以下查询无效
update table1 set name='HIGH' having age = max(age) group by type;
答案 0 :(得分:69)
我已经改变了Derek的剧本,现在它适用于我:
UPDATE table1 AS t
INNER JOIN
(SELECT type,max(age) mage FROM table1 GROUP BY type) t1
ON t.type = t1.type AND t.age = t1.mage
SET name='HIGH'
答案 1 :(得分:8)
您不能直接在更新语句中使用group by。它必须看起来更像这样:
update t
set name='HIGH'
from table1 t
inner join (select type,max(age) mage from table1 group by type) t1
on t.type = t1.type and t.age = t1.mage;
答案 2 :(得分:2)
您可以使用半连接:
SQL> UPDATE table1 t_outer
2 SET NAME = 'HIGH'
3 WHERE age >= ALL (SELECT age
4 FROM table1 t_inner
5 WHERE t_inner.type = t_outer.type);
3 rows updated
SQL> select * from table1;
NAME TYPE AGE
---------- ---------- ----------
HIGH 1 23
HIGH 2 26
HIGH 3 29
Raju 2 23
Babu 1 21
Muthu 3 27
6 rows selected
您的查询将无效,因为您无法通过查询直接在组中比较聚合值和列值。此外,您无法更新聚合。
答案 3 :(得分:0)
试试这个
update table1 set name='HIGH' having age in(select max(age) from table1 group by type);
答案 4 :(得分:0)
您可以使用以下代码。
Update table1#
inner Join (Select max(age) as age, type from Table1 group by Table1) t ON table.age = t.age#
Set name = 'High'#
答案 5 :(得分:0)
由于我查找了此回复并发现它有点令人困惑,因此我尝试确认以下查询起作用,从而确认了Svetlana高度评价的原始帖子:
update archives_forum f
inner join ( select forum_id,
min(earliest_post) as earliest,
max(earliest_post) as latest
from archives_topic
group by forum_id
) t
on (t.forum_id = f.id)
set f.earliest_post = t.earliest, f.latest_post = t.latest;
现在您知道...我也是如此。
答案 6 :(得分:-1)
您不能将GroupBy子句用于Update语句。您将不得不在此期间使用子查询
Update table1
Set name = 'High'
From table1
Join (Select max(age), type from Table1 group by Table1) t ON table1.age = t.age
答案 7 :(得分:-2)
update table1 set Name='HIGH' where Age in(select max(Age) from table1)
答案 8 :(得分:-2)
UPDATE table1 SET name = 'HIGH' WHERE age IN (SELECT MAX(age) FROM table1 GROUP BY name)