聚合表达式不能在WHERE子句中使用

时间:2019-05-16 20:31:54

标签: sql sql-server triggers

我的数据库中有以下表格:

enter image description here

第一个表名为Amount,第二个表名为Product,第三个表名为Purchase

我应该在插入到金额表上创建触发器。例如,我将插入以下值:4,1,10,其中4是id_purchase,1是id_product,4是此乘积的数量。触发器应从Amount_On_Stock中减去此金额。在我的示例中,应该是:48岁,变成38岁。

这是我的触发器的代码:

CREATE TRIGGER AmountInsert ON Amount
AFTER INSERT
AS
BEGIN
    UPDATE Product
    SET Amount_On_Stock = (
            SELECT 
                Amount_On_Stock 
            FROM Product
            WHERE ID_Product = (
                SELECT 
                    MAX(ID_Product) 
                FROM Purchase
                WHERE ID_Purchase = (
                    SELECT 
                        MAX(ID_Purchase) 
                    FROM Purchase
                )
            )
        )-(
            SELECT 
                Amount 
            FROM AMOUNT
            WHERE ID_Product = (
                SELECT 
                    MAX(ID_Product) 
                FROM Purchase
                WHERE ID_Purchase = (
                    SELECT 
                        MAX(ID_Purchase) 
                    FROM Purchase
                )
            )
            )
END

但是当我尝试创建此触发器时,出现以下错误:

  

除非在WHERE子句中使用聚合表达式,否则它不能使用   包含在HAVING子句的子查询或选择列表中,   并且正在汇总的列不是外部引用。

那么,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您的触发器看起来不像SQL Server触发器。我希望您的触发器看起来像这样:

CREATE TRIGGER AmountInsert ON Amount AFTER INSERT
AS
BEGIN
    UPDATE p
        SET Amount_On_Stock = p.Amount_On_Stock - i.amount
        FROM Product p JOIN
             inserted i
             ON p.ID_Product = i.ID_Product;
END;

但是,如果您同时在同一产品上有多个insert,这将无法正确解决问题。要处理您需要的聚合:

CREATE TRIGGER AmountInsert ON Amount AFTER INSERT
AS
BEGIN
    UPDATE p
        SET Amount_On_Stock = p.Amount_On_Stock - i.amount
        FROM Product p JOIN
             (SELECT i.ID_Product, SUM(i.amount) as amount
              FROM inserted i
              GROUP BY i.ID_Product
             ) i
             ON p.ID_Product = i.ID_Product;
END;