Select example:
SELECT campo1,
(ROUND(((t3.quantidade * t2.distancia *
(SELECT TOP 1 valor FROM frete WHERE datainicio <= t1.dataemissao AND tipo = t4.tipo ORDER BY DATAINICIO DESC))
- (t1.fretevalor - t5.pedagios))
/ (SELECT TOP 1 valor FROM diesel WHERE datainicio <= t1.dataemissao ORDER BY datainicio DESC),3)) saldo
FROM tabela1 t1
LEFT ...
In this example, I have only 2 columns ( campo1
and saldo
), saldo
computed by subquerys ( and so should be ) .
It is not the case to bring all relationships (JOINS) because the field is calculating correctly and should not be changed. The question is how to create the condition for column saldo
, according to its value.
It happens that, sometimes the value of column saldo
comes negative , so in this case, I'd like to put it as 0
value.
I can do with CASE
, but I would have to repeat 2x all this query (or not!), example:
SELECT campo1, ROUND((CASE WHEN
(((t3.quantidade * t2.distancia *
(SELECT TOP 1 valor FROM frete WHERE datainicio <= t1.dataemissao AND tipo = t4.tipo ORDER BY DATAINICIO DESC))
- (t1.fretevalor - t5.pedagios))
/ (SELECT TOP 1 valor FROM diesel WHERE datainicio <= t1.dataemissao ORDER BY datainicio DESC)) < 0
THEN 0 ELSE
(((t3.quantidade * t2.distancia *
(SELECT TOP 1 valor FROM frete WHERE datainicio <= t1.dataemissao AND tipo = t4.tipo ORDER BY DATAINICIO DESC))
- (t1.fretevalor - t5.pedagios))
/ (SELECT TOP 1 valor FROM diesel WHERE datainicio <= t1.dataemissao ORDER BY datainicio DESC))END),3) saldo
FROM tabela1 t1
LEFT ...
- Is there another way to compare value as
CASE
but without repeating the entire subquery (as in the example)?