Hola a todos:
Les cuento lo q tengo:
Tabla "t1"
Campos de tabla "t1"
(Producto, Importe)
Información de la tabla "t1"
-
1 15,50
3 8,50
9 5,00
-
Tabla "t2"
Campos de tabla "t2"
(Comprobante, Fecha, Producto, Cantidad, Importe, Activo)
Información de la tabla "t2"
-
1 xx-xx-xx 2 1 10,00 0
1 xx-xx-xx 5 1 8,00 1
1 xx-xx-xx 6 1 7,00 1
-
2 xx-xx-xx 1 1 2,00 1
2 xx-xx-xx 2 1 10,00 1
2 xx-xx-xx 9 1 7,50 1
-
3 xx-xx-xx 7 1 3,30 1
3 xx-xx-xx 1 1 2,00 1
-
4 xx-xx-xx 5 1 8,00 1
4 xx-xx-xx 6 1 7,00 1
-
Tabla "t3"
Campos de tabla "t3"
(Comprobante, Fecha, Importe)
Información de la tabla "t3" luego del proceso
1 xx-xx-xx 10,00
2 xx-xx-xx 20,50
3 xx-xx-xx 15,50
En tabla "t3" se agrega un registro, con la suma de uno o varios
productos, por cada comprobate en tabla "t2".
Los Productos de tabla "t2" que serán sumados son:
a) se suma t2.Importe si el producto tiene t2.Activo = 0
b) se suma (t1.Importe * t2.Cantidad) si el producto tiene t2.Activo =
1 y está en tabla "t1"
Esta es la codificación en cuestión:
INSERT INTO t3 (Comprobante, Fecha, Importe)
SELECT Comprobante, Fecha,
SUM(CASE
WHEN t2.Activo = 0 THEN
t2.Importe
WHEN t2.Activo = 1 AND t2.Producto IN (SELECT Producto FROM t1)
THEN
(SELECT Importe FROM t1 WHERE Producto = t2.Producto) *
t2.Cantidad
ELSE
0
END
) AS Importe
FROM t2
GROUP BY Comprobante, Fecha
HAVING
SUM(CASE
WHEN t2.Activo = 0 THEN
t2.Importe
WHEN t2.Activo = 1 AND t2.Producto IN (SELECT Producto FROM t1)
THEN
(SELECT Importe FROM t1 WHERE Producto = t2.Producto) *
t2.Cantidad
ELSE
0
END
) > 0
ORDER BY Comprobante, Fecha
El error es q no puedo tener subconsultas dentro de una función de
agregado.
Si alguien tiene algún aporte para solucionar esto será bienvenido.
Gracias
Pablo
Leer las respuestas