SQL 使用聚合函数更新查询
SQL Update Query with aggregate function
我有 2 个表:
CREATE TABLE [dbo].[Inventory](
[ID] [int] IDENTITY(1,1) NOT NULL
[SerialNo] [nvarchar](50) NOT NULL,
[Quantity] [decimal](12, 3) NULL)
CREATE TABLE [dbo].[InventoryDetails](
[ID] [int] IDENTITY(1,1) NOT NULL,
[InventoryID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[Quantity] [decimal](10, 3) NOT NULL)
我想执行这样的查询:
Update I set Quantity=Sum(ID.Quantity)
from Inventory I
Inner Join inserted ID on I.ID=ID.InventoryID
SQL 服务器出现此错误:
An aggregate may not appear in the set list of an UPDATE statement.
真正的方法是什么?我需要 Group By 子句吗?
我稍微修改了你的更新 sql 脚本,我认为它应该是这样的:
update Inventory as I
set I.Quantity = (select sum(ID.Quantity) from InventoryDetails as ID)
where I.ID = (select IDS.ID from InventoryDetails as IDS where IDS.ID = I.ID)
一点解释:
select sum(ID.Quantity) from InventoryDetails as ID
这 select 进行您想要的聚合。
where I.ID = (select IDS.ID from InventoryDetails as IDS where IDS.ID
= I.ID)
而这个模拟你的内部连接。 (如有错误请指正,谢谢)
我想代码是在 InventoryDetails table 上的触发器中使用的(因为它使用了特殊插入的 table)。在问题中指定它会很好。
这是SQL服务器的限制。它可以通过使用子查询来克服。
UPDATE I SET Quantity=ID.Sum_Quantity
FROM Inventory I
INNER JOIN (SELECT InventoryID, SUM(Quantity) AS Sum_Quantity
FROM inserted GROUP BY InventoryID) ID ON I.ID=ID.InventoryID
我有 2 个表:
CREATE TABLE [dbo].[Inventory](
[ID] [int] IDENTITY(1,1) NOT NULL
[SerialNo] [nvarchar](50) NOT NULL,
[Quantity] [decimal](12, 3) NULL)
CREATE TABLE [dbo].[InventoryDetails](
[ID] [int] IDENTITY(1,1) NOT NULL,
[InventoryID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[Quantity] [decimal](10, 3) NOT NULL)
我想执行这样的查询:
Update I set Quantity=Sum(ID.Quantity)
from Inventory I
Inner Join inserted ID on I.ID=ID.InventoryID
SQL 服务器出现此错误:
An aggregate may not appear in the set list of an UPDATE statement.
真正的方法是什么?我需要 Group By 子句吗?
我稍微修改了你的更新 sql 脚本,我认为它应该是这样的:
update Inventory as I
set I.Quantity = (select sum(ID.Quantity) from InventoryDetails as ID)
where I.ID = (select IDS.ID from InventoryDetails as IDS where IDS.ID = I.ID)
一点解释:
select sum(ID.Quantity) from InventoryDetails as ID
这 select 进行您想要的聚合。
where I.ID = (select IDS.ID from InventoryDetails as IDS where IDS.ID = I.ID)
而这个模拟你的内部连接。 (如有错误请指正,谢谢)
我想代码是在 InventoryDetails table 上的触发器中使用的(因为它使用了特殊插入的 table)。在问题中指定它会很好。
这是SQL服务器的限制。它可以通过使用子查询来克服。
UPDATE I SET Quantity=ID.Sum_Quantity
FROM Inventory I
INNER JOIN (SELECT InventoryID, SUM(Quantity) AS Sum_Quantity
FROM inserted GROUP BY InventoryID) ID ON I.ID=ID.InventoryID