【问题标题】:SQL Return all combinations from multiple rows/columnsSQL 返回多行/多列的所有组合
【发布时间】:2021-08-03 05:53:57
【问题描述】:

我有可能发生事件的表格(总和不等于 1),例如:

Outcome 1 - 0.1  Outcome 2 - 0.2  Outcome 3 - 0.4  Outcome 4 - 0.6
       

我想要所有可能的选择 - 比如:

P1 - 
0.1*(1-0.2)*(1-0.4)*(1-0.6) + 0.2*(1-0.1)*(1-0.4)*(1-0.6) + 0.4*(1-0.2)*(1-0.1)*(1-0.6) + 0.6*(1-0.2)*(1-0.4)*(1-0.1)

P2 - 
0.1*(0.2)*(1-0.4)*(1-0.6) + 0.2*(1-0.1)*(0.4)*(1-0.6) + 0.4*(1-0.2)*(1-0.1)*(0.6) + 0.6*(1-0.2)*(1-0.4)*(0.1) + 0.1*(1-0.2)*(0.4)*(1-0.6) + 0.6*(0.2)*(1-0.4)*(1-0.1)

P3 - 
0.1*0.2*0.4*(1-0.6) + 0.6*0.2*0.4*(1-0.1) + 0.1*0.6*0.4*(1-0.2) + 0.1*0.2*0.6*(1-0.4)

P4 -
0.1*0.2*0.4*0.6

结果 1,2,3,4 & P1,2,3,4 是列

【问题讨论】:

  • 我不明白这个问题。您的意思是方程式是列,或者您已插入数据 {0.1, 0.2, 0.4 & 0,6) 并且您希望查询使用这些插入的参数并将上述方程式的计算结果插入表中?
  • 这与 SQL 有什么关系?你的桌子是什么样子的?什么是列和行?如果你使用的是 SQL,什么数据库?请提供标签。

标签: sql combinations probability


【解决方案1】:

怎么样:

DROP TABLE if exists #temp;
SELECT

   0.1 as Outcome1,
   0.2 as Outcome2,
   0.3 as Outcome3,
   0.4 as Outcome4
INTO #temp;

SELECT 
   Outcome1 * (1-Outcome2) * (1-Outcome3) * (1-Outcome4) as P1,
   Outcome2 * Outcome1 * (1-Outcome3) * (1-Outcome4) as P2,
   Outcome3 * Outcome1 * Outcome2 * (1-Outcome4) as P3,
   Outcome4 * Outcome1 * Outcome2 * Outcome3 as P4
FROM #temp T1

输出:

P1             P2              P3                P4
-------------- --------------- ----------------- ------------------
0.0336         0.0084          0.0036            0.0024

DBFIDDLE

编辑:更新,因为我没有正确的定义:

SELECT
   0.1 as Outcome1,
   0.2 as Outcome2,
   0.4 as Outcome3,
   0.6 as Outcome4
INTO #temp;

SELECT 
   Outcome1*(1-Outcome2)*(1-Outcome3)*(1-Outcome4) + 
   Outcome2*(1-Outcome1)*(1-Outcome3)*(1-Outcome4) + 
   Outcome3*(1-Outcome2)*(1-Outcome1)*(1-Outcome4) + 
   Outcome4*(1-Outcome2)*(1-Outcome3)*(1-Outcome1)  as P1,
   Outcome1*(Outcome2)*(1-Outcome3)*(1-Outcome4) + 
   Outcome2*(1-Outcome1)*(Outcome3)*(1-Outcome4) + 
   Outcome3*(1-Outcome2)*(1-Outcome1)*(Outcome4) + 
   Outcome4*(1-Outcome2)*(1-Outcome3)*(Outcome1) + 
   Outcome1*(1-Outcome2)*(Outcome3)*(1-Outcome4) + 
   Outcome4*(Outcome2)*(1-Outcome3)*(1-Outcome1) as P2,
   Outcome1*Outcome2*Outcome3*(1-Outcome4) + 
   Outcome4*Outcome2*Outcome3*(1-Outcome1) + 
   Outcome1*Outcome4*Outcome3*(1-Outcome2) + 
   Outcome1*Outcome2*Outcome4*(1-Outcome3) as P3,
   Outcome1 * Outcome2 * Outcome3 * Outcome4 as P4
FROM #temp T1

输出:

P1      P2      P3      P4
0.4368  0.3128  0.0728  0.0048

更新DBFIDDLE

【讨论】:

  • 不,P1 是 [Outcome1 * (1-Outcome2) * (1-Outcome3) * (1-Outcome4)] + [Outcome2* (1-Outcome1) * (1-Outcome3) * ( 1-Outcome4)] + [Outcome3 * (1-Outcome2) * (1-Outcome1) * (1-Outcome4)] + [Outcome14* (1-Outcome2) * (1-Outcome3) * (1-Outcome1)]。我不想硬编码这个,让我知道是否有除此之外的解决方案
  • 没有(内置)函数可以进行这种思考,因此您必须对其进行硬编码。 (抱歉,我错过了复杂添加的部分内容,但缺少对应该发生的事情的解释......?)
  • 更新了公式,希望没有输入错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多