views:

60

answers:

2

I'm trying to do a query that returns the information of a purchase bill, but also there's another table that has detail of the bill, but I need to add that total to the other query, but I can't add the column, because it says that I need to have in the group by the same objects that in the select, and I tried it this way, but it says that it returns more than one value. Help please! :D

SELECT fc.fecha_factura_compra AS fecha, fc.id_factura AS no_factura, fc.serie,
       o.abreviatura + CAST(p.corr_id AS VARCHAR(255)) AS codigo_trupp, 
       p.nombre, fc.dias_credito, fc.tipo_cambio, 
       (SELECT SUM(dc.peso_neto * dc.precio_unitario) 
        FROM   detalle_compra AS dc 
        GROUP  BY dc.id_proveedor, 
                  dc.id_factura, 
                  dc.serie) AS total 
FROM   factura_compra AS fc, 
       origen AS o, 
       proveedor AS p, 
       detalle_compra AS dc 
WHERE  fc.id_proveedor = p.id_proveedor 
       AND dc.id_proveedor = p.id_proveedor 
       AND dc.id_factura = fc.id_factura 
       AND p.id_origen = o.id_origen 
       AND dc.serie = fc.serie 
       AND dc.id_factura = fc.id_factura 
       AND dc.id_proveedor = fc.id_proveedor 
       AND fc.activo_inactivo = 'true' 
       AND fc.anulada = 'false'
A: 

Instead of grouping by the columns, you should restrict the sub-select on the join columns and omit detalle_compra from the outer select:

SELECT fc.fecha_factura_compra as fecha,
       fc.id_factura as no_factura,
       fc.serie,
       o.abreviatura+CAST(p.corr_id as varchar(255)) as Codigo_Trupp,
       p.nombre,
       fc.dias_credito,
       fc.tipo_cambio,
       (select sum(peso_neto*precio_unitario)
          from detalle_compra
         where serie = fc.serie and
               id_factura = fc.id_factura and
               id_proveedor = fc.id_proveedor) as Total
  FROM factura_compra as fc,origen as o, proveedor as p
 WHERE fc.id_proveedor = p.id_proveedor and
       p.id_origen = o.id_origen and
       fc.activo_inactivo = 'true' and
       fc.anulada = 'false'

Side note: Use the BIT type to store booleans:

...
       fc.activo_inactivo = 1 and
       fc.anulada = 0
Marcelo Cantos
A: 

In the end, I added a view, and use the column from that view in my query :D thanks to everyone :D

Osukaa