sql >> Base de Datos >  >> RDS >> Mysql

Usar una unión con filas de datos agrupados

El problema es que cuando usas GROUP BY , solo puedes SELECT agregados y las columnas en las que se ha agrupado.

invoices.id es una columna que intentó seleccionar, pero no agrupó. Creo que probablemente quieras agregar esta columna a GROUP BY cláusula.

SELECT 
   invoices.id, 
   sum(grossTotal)-IFNULL(depositsCheck.previouslyPaid,0) as todayTotal, 
   depositsCheck.previouslyPaid, sum(grossTotal) as grossTotal  
FROM `invoices`    
    LEFT JOIN (SELECT SUM(amount) as previouslyPaid, invNo 
    FROM deposits 
    GROUP BY invNo) depositsCheck ON depositsCheck.invNo=invoices.id 
GROUP BY  invoices.paymentType, invoices.id ORDER BY id DESC

Para las tablas de ejemplo que diste, probablemente dará:

id    |    paymentType     |     grossTotal   |    dateTime   |   previouslyPaid
1     |         Cash       |        1000      |   UNIX TIME   |       150
2     |         Card       |        1350      |   UNIX TIME   |       350
3     |         Card       |        1250      |   UNIX TIME   |         0
4     |         Card       |        750       |   UNIX TIME   |         0

Pero en general, tendrás algo como:

id    |    paymentType     |     grossTotal   |    dateTime   |   previouslyPaid
1     |         Cash       |        1000      |   UNIX TIME   |       150
1     |         Card       |        1000      |   UNIX TIME   |       300
2     |         Cash       |        1350      |   UNIX TIME   |       350
2     |         Card       |        1350      |   UNIX TIME   |       350

Donde puede ver arriba, para la factura 1, 150 se pagaron en efectivo y 300 se pagaron con tarjeta.