0
I have a query that returns to me how much particular customer bought from a certain product.
The problem is in the item(product) because it has more than one feature that causes duplicity in the value that he purchased overall.
In the query is made the junction with the same table because I need to know how much he bought in general compared to, for example, 2018 e 2019.
OINV - tabela mãe onde pego o código do cliente.
INV1 - tabela filha da OINV onde fica o valor das vendas.
[DBO].[ItemCaracteristica] - View que retorna as características deste item.
DECLARE
@DATA INT
SET @DATA = 2019
SELECT
TB.Cliente,
TB.CODIGO,
TB.Descricao,
tb.Caracteristica,
TB.ANOAnterior,
TB.ValorAnterior,
TB.ANOATUAL,
[ValorAtual] = SUM(TB.ValorAtual)
FROM (
SELECT DISTINCT
[Cliente] = T0.CardCode,
[CODIGO] = T4.item,
[Descricao] = T4.Descricao,
[Caracteristica] = t4.caracteristica,
[ANOAnterior] = YEAR(T1.DocDate),
[ValorAnterior] = T3.LineTotal,
[AnoAtual] = YEAR(T0.DocDate),
[ValorAtual] = T2.LineTotal
--CASE WHEN YEAR(T1.DocDate) IS NULL THEN 100 ELSE SUM(T0.DocTotal) / SUM(T1.DocTotal) END,
--[CALCULO] = IIF(YEAR(T1.DocDate) IS NULL, 100 , SUM(T2.LineTotal) / SUM(T3.LineTotal))
FROM OINV T0
LEFT JOIN OINV T1 ON T0.CardCode = T1.CardCode AND YEAR(T1.DocDate) = @DATA -1
INNER JOIN INV1 T2 ON T0.DocEntry = T2.DocEntry AND T2.ItemCode = '1000'
LEFT JOIN INV1 T3 ON T1.DocEntry = T3.DocEntry AND T3.ItemCode = '1000'
INNER JOIN [DBO].[ItemCaracteristica] T4 ON T2.ItemCode = T4.Item
WHERE YEAR(T0.DocDate) = @DATA
AND T0.CANCELED = 'N'
--GROUP BY T0.Cardcode,T2.LineTotal, T3.LineTotal,YEAR(T1.DocDate), YEAR(T0.DocDate)
) AS TB
GROUP BY tb.Cliente, TB.CODIGO, TB.Descricao, tb.Caracteristica,
TB.ANOAnterior, TB.AnoAtual, ValorAnterior
You can concatenate the feature, so it will return only one line.
– Gaspar
The version of SQL management studio is 2014 it does not accept this function
– PAULO RAFAEL
The correct value would be 17.50 once and not twice as shown in the image attached. would be type to reset the other line.
– PAULO RAFAEL