Pregunta

I need help for this complex sql statement. In a select query, I need to add a statement to a calculated field with this structure:

If Field1 = 'value1' then


If Field2 = 0 then FCalculated1 = FieldA * FieldB

else FCalculated1 = FieldA * FieldC

end

FCalculated2 = FCalculated1 * FieldA


else if Field1 = 'value2' then


If Field2 = 0 then FCalculated2 = FieldD * FieldB

else FCalculated2 = FieldD * FieldE

end

FCalculated1 = FCalculated2 / FieldA


end

Basically I need to nest one conditional within another and use a calculated field as the source of another field. Does anyone can help me?

Thank you!!!

¿Fue útil?

Solución

Try this

declare @Field1 int
declare @Field2 int
declare @FCalculated1 int
declare @FCalculated2 int
declare @FieldA int
declare @FieldB int
declare @FieldC int
declare @FieldD int
declare @FieldE int
declare @Value1 int
declare @Value2 int

select @FCalculated2 = case
 when @Field1 = @Value1 then  case
  when @Field2 = 0 then @FieldA * @FieldB
  else @FieldA * @FieldC
  end * @FieldA
 when @Field1 = @Value2 then case
    when @Field2 = 0 then @FieldD * @FieldB
    else @FieldD * @FieldE
 end
end

select @FCalculated2

I mean I've used variables to get it to compile and test, just swap out the @ signs for your column names

Otros consejos

You can't have one column in a SELECT clause use the result of a different calculation in the same SELECT clause (essentially, because in SQL, all columns are potentially computed in parallel). Usually, I'd recommend a subselect to do the first calculation, but that doesn't seem reasonable here, so I'd just repeat the calculations:

select
CASE
    WHEN Field1 = 'value1' THEN
        CASE WHEN Field2 = 0 THEN FieldA * FieldB
            ELSE FieldA * FieldC
        END
    WHEN Field1 = 'value2' THEN
        CASE WHEN Field2 = 0 THEN FieldD * FieldB
            ELSE FieldD * FieldE
        END / FieldA
END as FCalculated1,
CASE
    WHEN Field1 = 'value1' THEN
        CASE WHEN Field2 = 0 THEN FieldA * FieldB
            ELSE FieldA * FieldC
        END * FieldA
    WHEN Field1 = 'value2' THEN
        CASE WHEN Field2 = 0 THEN FieldD * FieldB
            ELSE FieldD * FieldE
        END
END as FCalculated2
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top