First, as pointed out by OMG Ponies , you cannot refer to columns by their ordinal position. This is not an accident. The SQL specification is not built for dynamic schema in DDL or DML.
Given this, I need to wonder why you have your data structured in the same way as you. A mismatch between the schema and the problem domain occurs when you try to extract information. When queries are incredibly cumbersome to write, this indicates that the schema does not correctly model the domain for which it was designed.
However, be that as it may, given what you told us, the alternative solution would look something like this: (I assume that field_1*field1 should have been field_1 * field_1 or field_1 squared or Power( field_1, 2 ) )
Select 1 As Sequence, field_1 As [Field], Sfield_1 As [SField], Sfiled_1 As [SFiled] Union All Select 2, field_2, Sfield_2, Sfiled_2 ... Union All Select n, field_n, Sfield_n, Sfiled_n
Your request now looks like this:
With Inputs As ( Select 1 As Sequence, field_1 As [Field], Sfield_1 As [SField], Sfiled_1 As [SFiled] Union All Select 2, field_2, Sfield_2, Sfiled_2 .... ) , Results As ( Select Case When Sequence = 1 Then Power( [Field], 2 ) - ( [SField] * [SFiled] ) Else 1 / Power( [Field], 2 ) - ( [SField] * [SFiled] ) End As Result From Inputs ) Select Exp( Sum( Log( Result ) ) ) From Results
Thomas
source share