获取准备好的语句中按类别分组的行的COUNT和SUM


Getting the COUNT and SUM of rows grouped by category in a prepared statement

我准备了以下语句,它返回为特定类别找到的行:

if ($stmt = $mysqli->prepare("SELECT Work,Amount from work_times where Category=?")) {
    $stmt->bind_param("s", $category);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($work,$amount);
    while ($stmt->fetch()) {
    echo $work.": &pound;".$amount." each<br>";
    }

我想做的是将其调整为按"Work"列和"Amount"列对行进行分组,为每个组返回一行,并为每个行/组返回SUM和Count,这样我就可以输出如下内容:

5次咨询会议,每次50英镑:250英镑

2013年2月1日
2013年2月8日
2013年2月15日
2013年2月22日
2013年3月1日

3次治疗,每次40英镑:120英镑

2013年2月2日
2013年2月9日
2013年2月16日

2次治疗,每次20英镑40英镑

2013年2月3日
2013年2月10日

其中,每行中的粗体文本对应于:组中的行数、金额(针对每个会话)和组中每行的金额值之和。我希望这是清楚的!

不过,我不知道如何调整上面的陈述来实现这一点。

以上将是下表的结果:

ID | Work                | Amount
1  | Therapy Session     | £40     | 2013-02-02
2  | Consultancy Session | £50     | 2013-02-01
3  | Therapy Session     | £20     | 2013-02-03
4  | Consultancy Session | £50     | 2013-02-08
5  | Consultancy Session | £50     | 2013-02-15
6  | Therapy Session     | £40     | 2013-02-09
7  | Consultancy Session | £50     | 2013-02-22
8  | Therapy Session     | £40     | 2013-02-16
9  | Therapy Session     | £20     | 2013-02-10
10 | Consultancy Session | £50     | 2013-03-01

按照行数对组进行排序,就像上面的输出一样,这将是我想要的。

这应该有效:

SELECT `Work`, COUNT(*) AS sessions, SUM(`Amount`) AS Total
FROM work_times
GROUP BY `Work`, `Amount`

结果

|工作|课时|总计|------------------------------------------|咨询会议|5|250||治疗课程|2|40||治疗课程|3|120|

请参阅演示