在行组中显示结果并对每个组值求和

时间:2012-12-05 16:55:45

标签: php mysql

我对PHP / MySQL没有多少经验。我有一个包含3个字段的表格:idparticularamount,如下所示。

id   particular   amount
1    Fees         5000
2    Fees         3000
3    Bill         9000
4    Fees         4000
5    Bill         3000
6    Expense      2000
7    Fees         1000

我想分组显示数据以及每个组的总和,如下所示:

particular   amount
Fees         5000
Fees         3000
Fees         4000
Fees         1000
**Total        13000**
Bill         9000
Bill         3000
**Total        12000**
Expense      2000
**Total        2000**

我尝试此查询SELECT SUM(amount), particular FROM sale_expense GROUP BY particular并添加了所有值,但它未显示在组中,因为我需要显示数据

4 个答案:

答案 0 :(得分:2)

SELECT particular, id, sum(amount) amount
FROM TableName
GROUP BY particular, id WITH ROLLUP

fiddle

答案 1 :(得分:1)

试试这个sql:

SELECT particular, SUM(amount) AS total  FROM tablename GROUP BY particular

这应该给你每组的总数。
更新: 试试这个

$sql = "SELECT particular, SUM(amount) AS total  FROM tablename GROUP BY particular";
$result = mysql_query($sql);
while($row = mysql_fetch_array( $result )){
    $sql2 = "SELECT * FROM tablename WHERE particular = '".$row['particular']."'";
    $result2 = mysql_query($sql2);
    while($row2 = mysql_fetch_array( $result2 )){
        echo $row2['particular']. "  ".$row['amount'];
        echo "\n";
    }
    echo "Totol: ".$row['total']."";
}

答案 2 :(得分:0)

您可以将查询结合在一起:

select particular, amount
from ((select id, particular, amount
       from sales_expense se
      ) union all
      (select 99999 as id, concat('Total: ', particular), sum(amount) as amount
       from sales_expense se
       group by particular
      )
     ) t
group by particular
order by id

答案 3 :(得分:0)

试试这个:

( SELECT 
    particular, 
    amount  
  FROM sale_expense )
UNION
( SELECT 
    CONCAT(particular," - total") AS particular, 
    SUM(amount) AS amount 
  FROM sale_expense
  GROUP BY particular )
ORDER BY particular ASC