现在我确信这已经被问到并且在这里得到了很好的回答。但是,我无法找到答案,因为它涉及许多关键字。
我基本上想替换表格的表格:
Type amount param note
7 2 str1 NULL
42 12 str2 NULL
128 7 str3 samplenote
42 12 NULL NULL
101 4 str4 NULL
42 12 NULL NULL
7 1 str1 samplenote
128 2 str5 NULL
有一张像这样的桌子:
Type amount param note
7 3 str1 combined
42 36 NULL combined
128 9 NULL combined
101 4 str4 combined
换句话说,我试图根据其类型总结数量参数,同时为所有“不清楚”字段声明 param = NULL。(当组合类型的参数值具有多个不同的内容时,参数应为 NULL;否则,参数应具有原始内容。)
在我的 python 背景下,我使用 for 循环方法完成了这项任务,遍历类型,为每种类型添加一个新行,其中包含总计金额和 note = 'combined',然后删除剩余的行(见下文)。我敢肯定,某些 JOIN 语句必须有一种更有效的方法。但那会是什么样子呢?
仅供参考,这是我正在研究的解决方案(尚未运行!):
/*** dbo.sourcetable holds all possible Type values ***/
CREATE PROCEDURE [sumup]
AS
BEGIN
DECLARE @i int = (SELECT TOP (1) Type FROM [dbo].[sourcetable] ORDER BY Type)
DECLARE @MaxType int = (SELECT TOP (1) Type FROM [dbo].[sourcetable] ORDER BY Type DESC)
DECLARE @sum int
BEGIN TRY
WHILE @i <= @MaxType
BEGIN
IF EXISTS (SELECT * FROM [dbo].[worktable] WHERE Type = @i)
BEGIN
SET @sum = (SELECT SUM(amount) FROM [dbo].[worktable] WHERE Type = @i)
BEGIN
WITH cte AS (SELECT * FROM [dbo].[worktable] WHERE Type = @i)
INSERT INTO [dbo].[worktable]
([Type]
,[amount]
,[param]
,[note]
SELECT
cte.Type
,@sum
,cte.param
,'combined'
FROM cte
END
DELETE FROM [dbo].[worktable] WHERE Type = @i AND ISNULL([note],'') <> 'combined'
END
SET @i = @i + 1
END
END TRY
BEGIN CATCH
-- some errorlogging code
END CATCH
END
GO