簡體   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