Mysql

GROUP BY 列的總和,在 GROUP BY 中

  • November 20, 2017

我想顯示行 GROUP BY 主要參考 ID,然後顯示金額 GROUP BY 類型。

表結構

這是我的查詢

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` 

如果主要參考 id 和類型相同想要添加兩個行數量並且需要顯示為一行, 顯示圖像 請幫助我.. 提前致謝

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`

引用自:https://dba.stackexchange.com/questions/191288