SQL Server中所有组合的总和,而无需重复相同的值

时间:2019-05-17 04:47:07

标签: sql-server combinations

此链接确实提供了一种解决方案:

Sql Query : Sum , all the possible combination of rows in a table

这里的逻辑是

n! / k!(n-k)!     where k = 1 to n

但是我想要不重复的值

示例:TEMPTABLE

+----+-------+
| ID | Value |
+----+-------+
| 1  | 5000  |
| 2  | 5000  |
| 3  | 5000  |
| 4  | 5000  |
+----+-------+

对于此表,K应该为1,因为只有一种方式可以安排集合

所以组合将会是

5000
5000 + 5000 = 10000

5000 + 5000 + 5000 = 15000

5000 + 5000 + 5000 + 5000 = 20000

总共4种组合

4! / 1!(4-1)! = 4

对于以上答案,组合为

= 4 + 6 + 4 + 1 = 15 

其中11个结果相同

问题就在于如果有更多的条目,那么执行时间就会更多,所以我想在计算总数时删除那些重复的总数。

任何人都可以帮忙。

1 个答案:

答案 0 :(得分:0)

只需根据需要添加不同的或一组的

--To get the values
;With selfrec as (
  Select t.Value, t.ID, 0 as Level From #TempTable t
       UNION ALL
  Select t2.Value + t1.Value as Value, t1.ID, Level + 1 From #TempTable t1 
  Inner Join selfrec t2 on t1.ID < t2.ID 
  Where Level < 4 -- limit the number of recursions
)
Select Value 
From selfrec
Group by value 

-- To get the number of combinations 
;With selfrec as (
  Select t.Value, t.ID, 0 as Level From #TempTable t
       UNION ALL
  Select t2.Value + t1.Value as Value, t1.ID, Level + 1 From #TempTable t1 
  Inner Join selfrec t2 on t1.ID < t2.ID 
  Where Level < 4 -- limit the number of recursions
)
Select COUNT(DISTINCT Value) 
From selfrec