繁体   English   中英

使用group by子句的SQL Update查询

[英]SQL Update query with group by clause

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;

我已经改变了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'

您不能直接在更新语句中使用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;

您可以使用半连接:

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

您的查询将无法工作,因为您无法通过查询直接在组中比较聚合值和列值。 此外,您无法更新聚合。

你可以使用下面的代码。

Update table1#
inner Join (Select max(age) as age, type from Table1 group by Table1) t ON table.age = t.age#
Set name = 'High'#

由于我查看了这个回复并发现它有点令人困惑,我试验确认以下查询确实有效,证实了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;

现在你知道......我也是。

试试这个

update table1 set name='HIGH' having age in(select max(age) from table1 group by type);
update table1 set Name='HIGH' where Age in(select max(Age) from table1)
UPDATE table1 SET name = 'HIGH' WHERE age IN (SELECT MAX(age) FROM table1 GROUP BY name)

您不能将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM