intranet-queries/2016-09-06-Clientes_por_plazo_por_sucursal.sql

38 lines
1.0 KiB
SQL

-- Sales per payment type per customer/line/branch year to year
-- For Board Meeting presentation
SELECT
YEAR(dv.fecha) AS Year,
dv.id_sucursal AS Branch,
dv.id_cliente AS Customer,
COUNT(DISTINCT dv.id_cliente) AS Count_Customers,
IF(
(dv.fecha_vencimiento - dv.fecha) <= 5,
'cash',
'credit'
) AS Sale_conditions,
l.linea_analisis AS Line,
ROUND(
SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1)))/1000, 2
) AS Weight_MT,
SUM(dvi.valor) AS Value
FROM
documento_ventas dv
JOIN documento_ventas_has_item dvi
USING ( id_documento,id_sucursal )
JOIN item i
USING (id_item)
JOIN view_lineas l
USING (id_linea)
WHERE
(LEFT(dv.id_documento,2) = 'DV' OR
LEFT(dv.id_documento,2) = 'DE' OR
LEFT(dv.id_documento,2) = 'CF' OR
LEFT(dv.id_documento,2) = 'EI' OR
LEFT(dv.id_documento,2) = 'AI')
AND YEAR(dv.fecha) >= 2019
GROUP BY
Year, Branch, Sale_conditions, Customer, Line