使用Select和Sum插入

时间:2013-05-20 19:56:56

标签: sql-server sql-insert

所以我试图从另一个表的Select Query插入一个表。我想我必须这样做,因为我试图在插入内的几个列。最后,我希望这是一个存储过程,用于将数据从临时表移动到更规范化的数据。我得到的错误是查询中的最后一个字符的语法错误。您可以提供任何帮助或建议。这是我的疑问:

    INSERT INTO ShippingCost (WebOrder, Zone, NetAmount, EnteredWeight, BilledWeight,      Carrier)
SELECT WebOrder, Zone, NetAmount, EnteredWeight, BilledWeight, Carrier
FROM

    (select  substring([Package Reference Number 5],4,9) as WebOrder
             , zone
             , sum(CAST([Net Amount] as Money)) as NetAmount
             , sum(CAST([Entered Weight] as decimal)) as EnteredWeight
             , sum(CAST([Billed Weight] as INT)) as BilledWeight
             , 'UPS' as Carrier

               from UpsStaging
               where [Package Reference Number 5] LIKE 'WEB%[^0-9]%'
               group by [Package Reference Number 5],zone
    )

2 个答案:

答案 0 :(得分:0)

我认为您需要为派生表设置别名,即使您没有引用别名。在右括号后加上“x”。

答案 1 :(得分:0)

在子查询的末尾添加别名:

INSERT INTO ShippingCost (WebOrder, Zone, NetAmount, EnteredWeight, BilledWeight,      Carrier)
SELECT WebOrder, Zone, NetAmount, EnteredWeight, BilledWeight, Carrier
FROM
(select  substring([Package Reference Number 5],4,9) as WebOrder
 , zone
 , sum(CAST([Net Amount] as Money)) as NetAmount
 , sum(CAST([Entered Weight] as decimal)) as EnteredWeight
 , sum(CAST([Billed Weight] as INT)) as BilledWeight
 , 'UPS' as Carrier

   from UpsStaging
   where [Package Reference Number 5] LIKE 'WEB%[^0-9]%'
   group by [Package Reference Number 5],zone
) as [subq]

子查询是否有效?我不希望逐行工作 - 而是使用它:GROUP BY substring([Package Reference Number 5],4,9), zone