永发信息网

在sql中可以将计算出的平均值作为新的一列插入变中

答案:3  悬赏:30  手机版
解决时间 2022-01-01 05:50
  • 提问者网友:不爱我么
  • 2021-12-31 09:30
在sql中可以将计算出的平均值作为新的一列插入变中
最佳答案
  • 五星知识达人网友:从此江山别
  • 2021-12-31 09:37
不知道你要的是哪一种 看下面代码 应该有你要的
SQL> create table test1(id int,cnt int);

Table created.

SQL> insert into test1 values(1,10);

1 row created.

SQL> insert into test1 values(1,20);

1 row created.

SQL> insert into test1 values(1,30);

1 row created.

SQL> insert into test1 values(2,30);

1 row created.

SQL> insert into test1 values(2,50);

1 row created.

SQL> insert into test1 values(2,60);

1 row created.

SQL> commit;

Commit complete.

SQL> select * from test1;

ID CNT
---------- ----------
1 10
1 20
1 30
2 30
2 50
2 60

6 rows selected.

SQL> insert into test1 select id,avg(cnt) cnt from test1 group by id;

2 rows created.

SQL> commit;

Commit complete.

SQL> select * from test1;

ID CNT
---------- ----------
1 10
1 20
1 30
2 30
2 50
2 60
1 20
2 47

8 rows selected.

SQL> create table test2 as select * from test1;

Table created.

SQL> alter table test2 add (avgcnt int);

Table altered.

SQL> select * from test2;

ID CNT AVGCNT
---------- ---------- ----------
1 10
1 20
1 30
2 30
2 50
2 60
1 20
2 47

8 rows selected.

SQL> update test2 a set avgcnt=(select avg(cnt) from test2 b where a.id=b.id group by id);

8 rows updated.

SQL> commit;

Commit complete.

SQL> select * from test2;

ID CNT AVGCNT
---------- ---------- ----------
1 10 20
1 20 20
1 30 20
2 30 47
2 50 47
2 60 47
1 20 20
2 47 47

8 rows selected.

SQL>
全部回答
  • 1楼网友:杯酒困英雄
  • 2021-12-31 11:42
首先往表里追加一列。 update XXXX set avg_col=avg(c1,c2,.......,cn)
  • 2楼网友:独钓一江月
  • 2021-12-31 10:54
通过子查询,或者自定义函数来实现就行
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯