简体   繁体   English

根据表的一列对MySQL查询的结果进行分组

[英]Grouping results from MySQL query according to one column of table

I have the following query: 我有以下查询:

if ($stmt = $mysqli->prepare("SELECT Date, Due, Paid from patient_sessions WHERE Name=? AND Invoiced=? AND Type=? AND SUBSTR(Date,1,7)=? ORDER BY Date")) {

    $stmt->bind_param("ssss",$client,$invoiced,$type,$month);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($date,$due,$paid);

while ($stmt->fetch()) {

RUN SOMETHING HERE

}

Rather than use while ($stmt->fetch()) , which loops through all of the rows returned, I would like to group the rows returned by the value in the Due column, and then loop through each row per group, but I am not sure how to do this. 我不想使用while ($stmt->fetch())循环遍历所有返回的行,而是想对Due列中的值返回的行进行分组,然后遍历每组的每一行,但是不确定如何执行此操作。

EXTRA INFO 额外信息

I would like to return the results in the following format: 我想以以下格式返回结果:

One line for each 'Due' value returned with a count of the number of rows for each value (this is what the grouping is needed for). 对于每个“到期”值,返回一行,其中包含每个值的行数计数(这是分组所需要的)。

And then... 接着...

One line for each row, ordered by date where all of the 3 values (Date,Due,Paid) are displayed. 每行一行,按日期排序,显示所有3个值(日期,到期,付款)。

I am stuck because I need the grouping and also the individual rows. 我陷入困境是因为我需要分组以及各个行。 Can I return both with the one query? 我可以通过一个查询将两者都返回吗?

$sql = "SELECT Date, Due, Paid from patient_sessions 
        WHERE Name=? AND Invoiced=? AND Type=? AND SUBSTR(Date,1,7)=? 
        ORDER BY Due, Date";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssss",$client,$invoiced,$type,$month);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($date,$due,$paid);
$data = array();
while ($stmt->fetch())
{
    if (!isset($data[$due]))
    {
         $data[$due] = array();
    }
    $data[$due][] = array($date,$paid);
}
print_r($data);

Have a look at 'Group By' and 'Having' clauses. 查看“分组依据”和“具有”子句。

Will need more information to give you a real answer but hopefully these links will help. 需要更多信息才能为您提供真实的答案,但希望这些链接会有所帮助。

http://www.w3schools.com/sql/sql_having.asp http://www.w3schools.com/sql/sql_having.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM