2
Example of select:
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
), being the saldo
calculated by subquerys (and so it must remain).
It is not the case to bring all relations (JOINS), because the field is calculating correctly and should not be changed. The question is how to create the condition for the column saldo
, according to its value.
It turns out that, sometimes the value of the column saldo
comes negative, then in this case, I would like to put it as value 0
.
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 the value like the
CASE
but without repeating the whole subquery (as in the example)?
can use variable?
– Thiago Magalhães
@Thiagomagalhães I think it doesn’t work because it pulls the subquerys line by line, isn’t it?! Unless you create a @balance variable, and already use it for
CASE
. Is that it? If it’s not, then I have no idea.– rbz
Creating a function to calculate the balance can be an interesting solution.
– William John Adam Trindade
@Williamjohnadamtrindade can not, have to be direct in this query. I am using the
CASE
even, working, but I opened the question to see if there is a better way that does not require duplicate all the code.– rbz
Evaluate using APPLY in place of diesel and freight undercovers. // When the code starts to get hazy, it is because it is past the time to use CTE... ;)
– José Diz
@Josédiz very good! APPLY would be the
with
?– rbz
@Rbz No. the
with
is CTE, as proposed solution below. When possible read the suggested article.– José Diz
@Josédiz I found the CTE article, I took a look over it, really good, I will read in full as soon as possible! About the
APPLY
from what I found, only uses in functions, there is no way to do.– rbz