source

그룹별 절이 있는 SQL 업데이트 쿼리

itover 2022. 11. 12. 08:45
반응형

그룹별 절이 있는 SQL 업데이트 쿼리

Name         type       Age
-------------------------------
Vijay          1        23
Kumar          2        26
Anand          3        29
Raju           2        23
Babu           1        21
Muthu          3        27
--------------------------------------

각 유형의 최대 연령자 이름을 '로 업데이트하기 위한 쿼리를 작성합니다.높다.

그리고 왜 다음 쿼리가 작동하지 않는지 알려주세요.

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'

업데이트 스테이트먼트에서 직접 그룹을 사용할 수 없습니다.다음과 같이 해야 합니다.

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;

이 응답을 찾아보니 읽기에는 다소 혼란스러웠기 때문에 다음 쿼리가 효과가 있는지 확인하기 위해 실험하여 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;

이제 너도 알겠지만 나도 마찬가지야

세미 조인을 사용할 수 있습니다.

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 set name='HIGH' having age in(select max(age) from table1 group by type);

아래 코드를 사용할 수 있습니다.

Update table1#
inner Join (Select max(age) as age, type from Table1 group by Table1) t ON table.age = t.age#
Set name = 'High'#
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)

Update 문에 GroupBy 절을 사용할 수 없습니다.이 시간 동안 하위 쿼리를 사용해야 합니다.

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

언급URL : https://stackoverflow.com/questions/6898935/sql-update-query-with-group-by-clause

반응형