我正在尝试在一个表中显示来自两个查询的信息,但无法弄清楚如何使其工作。
这是我使用一个查询的原因:
SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;
Company Employees
ABC 45
DEF 15
GHI 5
现在,我希望有另一个查询,只计算所有行,给我全部员工数。
SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;
SELECT COUNT(*) AS Total FROM Employee_Table;
Company Employees
ABC 40
DEF 15
GHI 5
Total 60
这就是我的代码现在的样子。我为我想要回显的额外查询定义了两个额外的变量,但是相信这不是正确的方法,因为我得到了sqlsrv_fetch_array错误。
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$query2 = "SELECT COUNT(*) AS Totaal FROM Employee_Table;";
$result1 = sqlsrv_query($conn, $query1);
$result2 = sqlsrv_query($conn, $query2);
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=sqlsrv_fetch_array($result1, $result2)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
echo "</td><td>";
echo $row["Total"];
echo "</td></tr>";
}
echo "</table>";
如何实现这一目标?我很感激任何帮助
答案 0 :(得分:2)
首先正确
sqlsrv_fetch_array()
见http://php.net/manual/de/function.sqlsrv-fetch-array.php
只使用一个查询并使用mysqli_num_rows()函数计算
$ count = mysqli_num_rows($ result);
答案 1 :(得分:1)
我认为您可以通过仅使用第一个查询来实现此目的
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$result1 = mysql_query($conn, $query1);
$total_employee = 0;
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=mysql_fetch_array($result1)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
$total_employee += $row["count"];
echo "</td><td>";
echo "</td></tr>";
}
echo "<tr><td>Total</td><td>$total_employee</td></tr>";
echo "</table>";
答案 2 :(得分:1)
您只能使用一个查询:
$result = sqlsrv_query($conn, "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC");
?>
<table id='total'>
<tr><th>Company</th><th>Amount of employees</th></tr>
<?php
$total = 0;
while ($row=sqlsrv_fetch_array($result)) {
$total += $row["count"];
?>
<tr><td><?= $row["Company"] ?></td><td><?= $row["count"] ?></td></tr>
<?php
}
?>
<tr><td></td><td><?= $total ?></td></tr>
</table>
<?php
答案 3 :(得分:0)
尝试以下代码
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$query2 = "SELECT COUNT(*) AS Totaal FROM Employee_Table;";
$result1 = sqlsrv_query($conn, $query1);
$result2 = sqlsrv_query($conn, $query2);
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=sqlsrv_fetch_array($result1)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
echo "</td><td>";
echo "</td></tr>";
}
$rows = sqlsrv_fetch_array($result1)
echo "<tr><td>";
echo $rows["Total"];
echo "</td></tr>";
echo "</table>";