来自不同表的列的总和

时间:2018-10-23 10:18:21

标签: sql sql-server

这是我的数据,

表1:

             STORAGE    HANDLING    TOTAL BILLING 
             -------------------------------------- 
                 1300    10900     
                    0    10950     
                     0    6000     
                     0    5950     

表2:

 LINER REVENUE 
--------------- 
       1300 
        250 
       3000 
        200 

我需要计算总帐单:

我尝试使用此代码。

UPDATE [dbo].[FCLOverall] SET [Total Revenue] = SELECT SUM([STORAGE]),      SUM([HANDLING]), SUM([LINER Revenue])
FROM (SELECT [STORAGE], [HANDLING],[Container No]
       FROM [dbo].[FCLOverall]
      UNION ALL
     SELECT [Container No],[LINER Revenue]
       FROM [dbo].[FCL_Child]) 

它抛出一些错误,缺少括号和无效的关键字选择。查询是对还是错?

有人可以指导查询如何计算吗?

3 个答案:

答案 0 :(得分:1)

您在下面找到了什么

 UPDATE [dbo].[FCLOverall]
    SET [Total Revenue] = 
   (SELECT SUM([STORAGE])+ SUM([HANDLING]) + SUM([LINER Revenue] ) as s
    FROM  (
        SELECT [Container No],[STORAGE], [HANDLING],0
           FROM [dbo].[FCLOverall]
          UNION ALL
         SELECT [Container No],0,0,[LINER Revenue]
           FROM [dbo].[FCL_Child]
             ) t ) 

答案 1 :(得分:0)

基于“容器号”为关键字段的假设进行尝试。

UPDATE U
SET U.[Total Revenue] = COALESCE(U.Storage,0) + COALESCE(U.Handling,0) + COALESCE(FCLC.[Liner Revenue],0)
FROM dbo.FCLOverall AS U
INNER JOIN dbo.FCL_Child AS FCLC
  ON U.[Container No] = FCLC.[Container No]

答案 2 :(得分:-1)

尝试一下:

webpack-merge