[英]Count rows in a SQL group
I have a script that I want to put on a dashboard. 我有一个要放在仪表板上的脚本。 The SQL works and groups the items in the while and it is displayed in the dashboard correctly.
SQL会在一段时间内对项目进行分组并将其正确显示在仪表板中。 However I also want the QTY's to show.
但是我也想显示数量。
So if the SQL is grouping how can I count the rows it returns so I can echo the QTY out in to my table for each row. 因此,如果SQL进行分组,我该如何计算它返回的行,以便可以将QTY回显到每一行的表中。 This is my code.
这是我的代码。
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
$custid = $row['CustomerID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "SELECT * FROM stock
JOIN hardware ON stock.HardwareID = hardware.HardwareID
WHERE stock.CustomerID = $custid GROUP BY stock.HardwareID";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row1['Hardware']."</td>";
echo "<td></td>";
echo "</tr>";
}
}
?>
So the aim is to have the row 所以目的是要排
echo "<td></td>";
Have a variable in it that shows the qty for each row that is grouped. 其中包含一个变量,该变量显示分组的每一行的数量。
you can use this query, group by query has to select and provide aggregation, here i have provided count, if you require some of appropriate column you can change it accordingly... 您可以使用此查询,按查询分组必须选择并提供汇总,这里我提供了计数,如果您需要一些适当的列,则可以相应地更改它...
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
$custid = $row['CustomerID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "SELECT stock.Hardwareid, count(*) as CountHardware FROM stock
JOIN hardware ON stock.HardwareID = hardware.HardwareID
WHERE stock.CustomerID = $custid GROUP BY stock.HardwareID";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row1['Hardware']."</td>";
echo "<td></td>";
echo "</tr>";
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.