【问题标题】:SUM() works fine in select statement but returns NULL in Insert statementSUM() 在 select 语句中工作正常,但在 Insert 语句中返回 NULL
【发布时间】:2013-06-12 15:45:13
【问题描述】:

我正在创建一个脚本,通过某些 ID 矩阵 ID 来总结损益 (PL)。我对视图“vw_package”使用以下 SQL 语句:

select trade_matrix_id, sum(pl) from vw_package 
where date (gen_timestamp) between '2012-05-01' and '2012-05-30' 
and trade_matrix_id between 30 and 60
group by trade_matrix_id;

它正确地产生了这个结果:

trade_matrix_id,sum(pl)
41,            -147.33
42,             -27.45
43,            -329.03
44,            -329.03
45,            -329.03
...

现在我想用这些结果填写一张表格。我在脚本中创建了一个表格:

CREATE TABLE IF NOT EXISTS PLByMatrixID 
    (trade_matrix_id    int,
    Sum_PL              float(19,2));

我使用 INSERT 命令用与上面完全相同的 SELECT 语句填充表:

insert into PLByMatrixID (trade_matrix_id, Sum_PL)
   select trade_matrix_id, sum(pl) from vw_package 
   where date (gen_timestamp) between '2012-05-01' and '2012-05-30' 
   and trade_matrix_id between 30 and 60
   group by trade_matrix_id;

我调用脚本并查询结果表PLByMatrixID,PL中的所有值都是NULL:

41,            NULL
42,            NULL
43,            NULL
...

如果有人能告诉我我在这里缺少什么,我将不胜感激。

【问题讨论】:

  • 你使用的是什么关系型数据库?
  • 您确定您阅读的结果正确吗?也许那里有错误。插入语句看起来是正确的。

标签: sql insert null sum


【解决方案1】:

试试

   select trade_matrix_id, sum(pl)
   into PLByMatrixID 
   from vw_package 
   where date (gen_timestamp) between '2012-05-01' and '2012-05-30' 
   and trade_matrix_id between 30 and 60
   group by trade_matrix_id;

【讨论】:

  • 如果没有额外的数据,Select into 当然可以,但最好能弄清楚插入失败的原因。
  • ypercube:如果我阅读的结果正确,我不确定你的问题是什么意思。我从 PLByMatrixID 运行 select * 并且 PL 列仅包含 NULL。你问的是这个吗?
  • BaN3:当我尝试 MySQL 返回“未声明的变量:PLByMatrixID”时。我还尝试将表 PlByMatrixID 创建为 select .... 希望它能以正确的格式创建 PL 列(float (19,2) 但这也无济于事。我怀疑它要么是转换问题或 MySQL 不喜欢 SUM() 和 group by。
猜你喜欢
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 2011-12-04
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
相关资源
最近更新 更多