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

Usar grupo por subconsulta interna

Puede usar la siguiente consulta para su conjunto de resultados esperado

SELECT *,
COALESCE(
    (SELECT SUM(pt.rupees) FROM (
        SELECT  MONTH(`date`) `month`,
        MAX(id) id,
        SUM(rupees) rupees
        FROM house_details 
        GROUP BY `month`,subincome
    ) pt 
    WHERE CASE WHEN pt.month = t1.month THEN pt.id < t1.id ELSE pt.month < t1.month END 
), 0) AS progressive_total,
(SELECT SUM(rupees) FROM(
        SELECT  MONTH(`date`) `month`,
        MAX(id) id,
        SUM(rupees) rupees
        FROM house_details 
        GROUP BY `month`,subincome
    ) cs 
    WHERE  CASE WHEN cs.month = t1.month THEN cs.id <= t1.id ELSE cs.month <= t1.month END 
) AS cumulative_sum 
FROM (
    SELECT MONTHNAME(t.date) AS `monthname`,
    MAX(id) id,
    MONTH(t.date) `month`,
    YEAR(t.date) AS `year`,
    GROUP_CONCAT(t.income) income,
    t.subincome,
    GROUP_CONCAT(t.ssubincome) ssubincome,
    SUM(rupees) AS amount,
    GROUP_CONCAT(receipt_id) AS receipt_ids 
    FROM house_details t 
    WHERE YEAR(t.date) = YEAR(CURRENT_DATE()) 
    GROUP BY `monthname`,`month`, t.subincome
    ORDER BY `month`
) t1

Demostración