我需要构建一个SQL查询,但我不知道该怎么做。如果有人帮忙,我会非常喜欢它。
我有下表
GroupedBYField ConditionField ToBeSummeField
1 1 1
1 1 2
1 1 3
2 2 100
2 2 200
2 2 300
我需要获得groupedBYField, SUM(ToBeSummeField)
的所有可能组合
SUM(conditionField) = 2
,即下表
GroupedBYField SumField
1 3
1 4
1 5
2 100
2 200
2 300
感谢您的帮助!
答案 0 :(得分:5)
我相信这有效。它应该也适用于ConditionField值为0的情况 它将在SQL 2005/2008上运行。
它使用递归CTE来处理添加到所需值的任意数量的潜在行
DECLARE @t TABLE
(GroupedBYField INT
,ConditionField INT
,ToBeSummeField INT
)
INSERT @t
SELECT 1,1,1
UNION SELECT 1,1,2
UNION SELECT 1,1,3
UNION SELECT 2,2,100
UNION SELECT 2,2,200
UNION SELECT 2,2,300
;WITH numCTE
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY GroupedBYField
,ConditionField
,ToBeSummeField
) AS id
,*
FROM @t
)
,myCTE
AS
(
SELECT id
,GroupedBYField
,ConditionField
,ToBeSummeField
,'|' + CAST(id AS VARCHAR(MAX)) + '|' AS LEVEL
FROM numCTE
UNION ALL
SELECT t.id
,t.GroupedBYField
,m.ConditionField + t.ConditionField
,m.ToBeSummeField + t.ToBeSummeField
,m.LEVEL + '|' + CAST(t.id AS VARCHAR(11)) + '|' AS LEVEL
FROM myCTE AS m
JOIN numCTE AS t
ON t.id > m.id
AND t.GroupedBYField = m.GroupedBYField
AND m.LEVEL NOT LIKE '%|' + CAST(t.id AS VARCHAR(MAX)) + '|%'
)
SELECT GroupedBYField
,ToBeSummeField
FROM myCTE
WHERE ConditionField = 2 -- amend this value change the target sum
ORDER BY 1,2
OPTION (MAXRECURSION 0)
编辑 - 添加了maxrecursion 0以允许它在任意数量的源行上工作