sql >> Database teknologi >  >> RDS >> Mysql

Sådan stopper du denne gentagelse og grupperer efter dato

Yon skal bruge en UNION i underforespørgslen og derefter GROUP BY i SELECT:

SELECT my_date, 
       my_month, 
       SUM(credit), 
       SUM(debit)
FROM (
    SELECT cc.credit_date as my_date,
           MONTHNAME(cc.credit_date) as my_month,
           ROUND(SUM(IFNULL(cc.credit_amount,0)),2) AS credit,
           0 AS debit
    FROM   cust_credit cc
    WHERE YEAR(cc.credit_date) = YEAR(NOW()) 
    GROUP BY cc.credit_date,
             MONTHNAME(cc.credit_date)
    UNION
    SELECT 
           cd.debit_date ,
           MONTHNAME(cd.debit_date) ,
           0 ,
           ROUND(SUM(IFNULL(cd.debit_amount,0)),2)
    FROM   cust_debit cd
    WHERE YEAR(cd.debit_date) = YEAR(NOW()) 
    GROUP BY cd.debit_date, 
             MONTHNAME(cd.debit_date) 
) as TT
GROUP BY my_date,my_month

This is the Fiddle



  1. MySql-forespørgsel:medtag dage, der har COUNT(id) ==0, men kun inden for de sidste 30 dage

  2. Hvordan refererer jeg til overordnet tabel i en multitabel join?

  3. #1111 - Ugyldig brug af gruppefunktion

  4. Samme forespørgsel - forskellige eksekveringsplaner