是否有一种方法可以使用公式上多个行(按每个组划分)的结果。
我有以下公式:
result = (1st vfg ) / (1 + (1st vfg / 2nd vfg) + (1st vfg / 3rd vfg) + ... + (1st vfg / *nth* vfg) )
vfg =组中的值
例如,下表如下:
Group | Value
---------------
1 | 1000
1 | 280
1 | 280
2 | 1000
注意:我保证第一个表的值中不会有0(零)或NULL
应该给我以下结果:
Group | Result
---------------
1 | 122.85
2 | 1000 -> If there is only one value on the group, the result will be the value itself
答案 0 :(得分:1)
您需要一列来指示组内的行顺序(时间戳,序列号,标识列等)。数据库表中的行没有隐式顺序。一旦有了这些,就可以使用CTE和窗口函数来解决问题:
;WITH
cte AS
(
SELECT [Group]
, [Value]
, FIRST_VALUE([Value]) OVER (PARTITION BY [Group] ORDER BY RowOrder) AS FirstValue
, FIRST_VALUE([Value]) OVER (PARTITION BY [Group] ORDER BY RowOrder) / [Value] AS Subtotal
FROM MyTable
)
SELECT [Group]
, AVG(FirstValue) / SUM(Subtotal) AS Result
FROM cte
GROUP BY [Group]