【发布时间】:2019-11-20 05:09:51
【问题描述】:
如何在 TSQL 中聚合来自不定数量组的信息? 例如。我们有一个包含 2 列的表 - 客户和区域。
Clients Regions
client1 45
client1 45
client1 45
client1 45
client1 43
client1 42
client1 41
client2 45
client2 45
client3 43
client3 43
client3 41
client3 41
client3 41
client3 41
每个客户端都可以有任意数量的区域。
在下面的示例中:client1 有 4 组区域,第 2 - 1 组,第 3 - 2 组。
我想计算每个客户的 gini 杂质,即计算 - 客户区域的差异有多大。
为此,我想对每个客户应用以下公式:
1 - ((% of region1 among all the regions in the client) ^ 2 +
(% of region2 among all the regions in the client) ^ 2 +
… (% of regionN among all the regions in the client) ^ 2)
但是区域的数量是不确定的(每个客户端可能不同)。
这应该是计算出来的:
client1 = 1 - ((4 / 7 ) ^ 2 + (1 / 7 ) ^ 2 + (1 / 7 ) ^ 2 + (1 / 7 ) ^ 2)
client2 = 1 - ((2 / 2 ) ^ 2)
client3 = 1 - ((2 / 6 ) ^ 2 + (4 / 6 ) ^ 2)
这是理想的输出:
Clients Impurity
client1 61%
client2 0%
client3 44%
您能提示我解决问题的方法吗?
【问题讨论】:
-
一步一步来。编写查询以获取每个客户的计数。编写查询以获取每个客户端和区域的计数。将两者结合起来,以获得百分比。汇总,因此您可以总结百分比的幂。
-
根据示例数据,预期的输出是什么?谢谢。
-
将预期输出添加到主题
标签: sql sql-server tsql gini