2014-02-05 13 views
0

我有表T1,它有3個文本列:a,b,c。 現在我想創建表T2出T1使用下面的查詢創建表作爲從條款中選擇

create table T2 as 
    select 
    a,b, sum(c) as sum_col 
    from T1 
    where 'some where condition here' 

現在列sum_col與數據類型double,在那裏,我希望它創建爲decimal(20,7)創建。 有人可以建議有辦法做到這一點嗎?

回答

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) 
+0

我使用MySQL,其給出語法錯誤:「語法錯誤,意外DECIMAL_SYM」關於十進制(20, 7) –

+0

不,我也有MySQL。查看添加到答案的SQLFiddle演示。 –

+0

我試了一下。適用於我。 –

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;