【发布时间】:2018-01-30 07:38:33
【问题描述】:
我有一个 SQL.Table
CREATE TABLE [dbo].[Stack_Example](
[ID] [bigint] NOT NULL,
[Product_ID] [bigint] NULL,
[Quantity] [decimal](18, 2) NULL,
[Price] [decimal](18, 2) NULL,
CONSTRAINT [PK_Stack_Example] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
数据如下所示:
INSERT [dbo].[Stack_Example] ([ID], [Product_ID], [Quantity], [Price]) VALUES (1, 25, CAST(55.00 AS Decimal(18, 2)), CAST(1000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Stack_Example] ([ID], [Product_ID], [Quantity], [Price]) VALUES (2, 25, CAST(1.00 AS Decimal(18, 2)), CAST(1000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Stack_Example] ([ID], [Product_ID], [Quantity], [Price]) VALUES (3, 26, CAST(1.00 AS Decimal(18, 2)), CAST(500.00 AS Decimal(18, 2)))
GO
所以我的问题是我需要按价格、产品 ID 和总和(数量)对这些项目进行分组。
假设我的输出窗口需要看起来像这样,则需要更新/删除查询
选择查询很简单
select Product_ID,SUM(Quantity) AS Quantity,Price from Stack_Example
Group by Product_ID,Price
所以一开始我需要做的是删除 id 为 2 的行并更新 id 为 1 的行 set Quantity = Quantity + 1 ( Quantity of deleted row )。
所以当我运行选择查询而不分组和求和时,我需要得到相同的输出
UPDATE Stack_Example SET Quantity = (SELECT SUM(Quantity)
FROM Stack_Example child
WHERE child.Product_ID = Stack_Example.Product_ID
GROUP BY Product_ID)
DELETE FROM Stack_Example WHERE ID IN (SELECT TOP 1 ID
FROM Stack_Example
WHERE Product_Id IN ( (SELECT TOP 1 Product_ID
FROM Stack_Example
GROUP BY Product_ID
HAVING COUNT(Product_ID)>1)))
【问题讨论】:
-
对不起,我无法清楚地了解您真正想要什么。
标签: sql sql-server