【问题标题】:Sum of all combination in SQL Server without repeating same valuesSQL Server 中所有组合的总和,不重复相同的值
【发布时间】:2019-05-17 15:15:04
【问题描述】:

此链接确实提供了一个封闭的解决方案:

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 个结果相同

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

谁能帮忙。

【问题讨论】:

    标签: sql-server combinations


    【解决方案1】:

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

    --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
    

    【讨论】:

    • 问题是如果有更多的条目,执行时间会更长,所以我想在计算总数时删除那些重复的总数。
    • 是一个递归函数,无论如何您都需要计算每个组合,将验证添加到 CTE 对性能的影响会比这更大,此外,在递归 CTE 中无法使用递归表达式不止一次(例如,添加 EXISTS 条件)
    • 好的,但是我们可以在没有 Recursive CTE 的情况下做到这一点吗?
    • 另一种方法是使用临时表和循环,但无论如何他们需要迭代所有组合并检查值是否已经存在,成本将是相同的。我认为这是最好的选择
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多