SUM of column by GROUP BY which is WHithin a GROUP BY i want to display the rows GROUP BY main Reference Id and then show the amount GROUP BY type.



this my query

SELECT gl.`drcr`,gl.`amount`,gl.`name`,gl.`type`,
       gl.`narration`,gl.`main_reference`,gl.`date` "        
. "FROM `general_ledger` AS gl "
. "INNER JOIN ( "
. " SELECT SUM(amount) AS total 
    FROM `general_ledger` GROUP BY `type` ) AS tot "
. "WHERE gl.`date` BETWEEN '$start_date' AND '$end_date' "
. "GROUP BY gl.`main_reference`,gl.`date`,gl.`name`,
            gl.`type`,gl.`amount`,gl.`drcr`,gl.`narration` 


if main reference id and type same want to add both row amount and need to display as one row like

please help me.. 
thanks in advance
SELECT `drcr`,SUM(`amount`) 
`amount`,`name`,`type`,`narration`,`main_reference`,`date`
FROM (
    SELECT gl.`drcr`,gl.`amount`,gl.`name`,gl.`type`,gl.`narration`,gl.`main_reference`,gl
  .`date` "
                              . "FROM `general_ledger` AS gl "
                              . "INNER JOIN ( "
                              . " SELECT SUM(amount) AS total FROM `general_ledger` GROUP BY `type` ) AS tot "
                              . "WHERE gl.`date` BETWEEN '$start_date' AND '$end_date' "
                              . "GROUP BY gl.`main_reference`,gl.`date`,gl.`name`,gl.`type`,gl.`amount`,gl.`drcr`,gl.`narration` 
) Interimresults
GROUP BY `drcr`, `name`,`type`,`narration`,`main_reference`,`date`