计算列的SQL内部联接

时间:2017-12-06 06:51:19

标签: sql sql-server

我想将销售年度设置为自动等于帐户代码相等的发票标题总和。

ALTER TABLE DEBTORS_MASTER  
    ALTER COLUMN Sales_Year_To_Date AS 
          (SELECT SUM (INVOICE_HEADER.Total_Sell_Amount_Excl_VAT)
           FROM DEBTORS_MASTER
           INNER JOIN DEBTORS_MASTER ON INVOICE_HEADER.Account_Code = DEBTORS_MASTER.ACCOUNT_CODE);

我收到此错误

  

关键字' AS'

附近的语法不正确

2 个答案:

答案 0 :(得分:0)

我认为你必须单独做到这一点

修改声明

ALTER TABLE DEBTORS_MASTER
ALTER COLUMN Sales_Year_To_Date INT

更新声明

UPDATE t1
SET Sales_Year_To_Date = Sales_Year_To_Date
FROM DEBTORS_MASTER t1
INNER JOIN (
    SELECT SUM(INVOICE_HEADER.Total_Sell_Amount_Excl_VAT) AS Sales_Year_To_Date
    FROM DEBTORS_MASTER
    INNER JOIN DEBTORS_MASTER ON INVOICE_HEADER.Account_Code = DEBTORS_MASTER.ACCOUNT_CODE
    ) t2 ON t2.ACCOUNT_CODE = t1.ACCOUNT_CODE

答案 1 :(得分:0)

您可以使用此代码

UPDATE DM
SET Sales_Year_To_Date = IH.sumAmount
FROM DEBTORS_MASTER AS DM
INNER JOIN
    (
        SELECT Account_Code, SUM(Total_Sell_Amount_Excl_VAT) sumAmount
        FROM INVOICE_HEADER
        GROUP BY Account_Code
    ) IH
ON IH.Account_Code = DM.Account_Code