OPTION 1: nest the query in a subtable with DISTINCT
It is assumed that you only have one price per note, and therefore, only one repetition per note will be generated.
select SUM(subtabla.Total) from
(select DISTINCT nota, Total
where FechaGasto >='2017-01-01'and FechaGasto<='2017-12-31' and
NombrePartida like '%activo%') as subtabla
OPTION 2: use the GROUP BY combined with MAX or 1
Group by
is a function that will group the results by the field that
you suggest The power of these functions is used because
In addition, the summation fields, such as SUM, perform the aggregation
based on the GROUP BY
field.
If you also have me account that MAX
will give you the maximum value of one of the notes, you will only get one per line, and not the two occurrences.
select nota, MAX(Total) as Total into #agrupada
from Gastos
where FechaGasto>='2017-01-01'and FechaGasto<='2017-12-31' and
NombrePartida like '%activo%'
GROUP BY nota
Here you will have the temporary table #agrupada
only with the max per note, that is one line per note.
So check the temporary table now, and you'll see the total
select sum(Total) from #agrupada
You can do the same also by nesting the table in the from, as in the initial option.
Assuming that for each note you will always have the same "Total". you can also do (in two steps, with temporary table)
select DISTINCT Nota, Total into #agrupada
from Gastos
where FechaGasto>='2017-01-01'and FechaGasto<='2017-12-31' and
NombrePartida like '%activo%'
GROUP BY nota
select sum(Total) from #agrupada
OPTION THAT CALCULATES VAT ACCORDING TO FIELD VAT
Regarding the comment, the following query is also generated
select sum(Total)
from (
SELECT distinct nota,
CASE
WHEN iva = 1 THEN totalxproducto * 1.16
WHEN iva = 0 THEN totalxproducto
END as Total
from Gastos
where FechaGasto>='2017-01-01'and FechaGasto<='2017-12-31
and NombrePartida like '%activo%'
)
Most optimized option (you do not need to delete duplicates)
SELECT SUM(CASE
WHEN iva = 1 THEN totalxproducto * 1.16
WHEN iva = 0 THEN totalxproducto
END)
from Gastos
where FechaGasto>='2017-01-01'and FechaGasto<='2017-12-31
and NombrePartida like '%activo%'
Some links:
link
link