我有表T1,它有3个文本列:a,b,c。 现在我想使用以下查询
创建T1中的表T2create table T2 as
select
a,b, sum(c) as sum_col
from T1
where 'some where condition here'
现在使用数据类型sum_col
创建列double
,我希望将其创建为decimal(20,7)
。
任何人都可以建议有办法吗?
答案 0 :(得分:3)
您可以使用cast
函数为派生列定义新数据类型。
create table T2 as
select a,b, cast( sum(c) as decimal(20,7) ) as sum_col
from T1
where 'some condition here'
MySQL小提琴:Demo
MySQL命令提示符下的内联演示:
mysql> create table t1( i int );
mysql> desc t1;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| i | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
mysql> insert into t1 values( 6 ), ( 9 );
Query OK, 2 rows affected (0.03 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> create table t2 as
-> select cast( sum(i) as decimal(20,7) ) as sum_total
-> from t1;
Query OK, 1 row affected (0.45 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> desc t2;
+-----------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------+------+-----+---------+-------+
| sum_total | decimal(20,7) | YES | | NULL | |
+-----------+---------------+------+-----+---------+-------+
1 row in set (0.02 sec)
mysql> select * from t2;
+------------+
| sum_total |
+------------+
| 15.0000000 |
+------------+
1 row in set (0.00 sec)
答案 1 :(得分:0)
试一试。此示例将列a和b设置为数据类型int
create table T2 (a int, b int, sum_col decimal(20,7))
select a,b, sum(c) as sum_col from T1 where
尝试总和
create table T2 (a int, b int, sum_col decimal(20,7))
select '1' a, '1' b, sum(1*3) as sum_col;