我有一个订单表,我正在查询总数,我希望按季度显示它们。这是查询:
SELECT shipping_number, SUM(qty) AS qty, SUM(cost) AS cost,
QUARTER( TIME ) AS quarter
FROM order_items
WHERE 1
GROUP BY quarter, shipping_number
ORDER BY quarter, shipping_number
我有一个简单的表格行,我想在其中显示以下结果:
echo "<tr>";
echo '<th colspan="2" style="text-align: right !important; ">TOTAL QUEBEC - EASTERN CANADA</th>';
echo "<th>Amount<br />Quantity</th>";
foreach($results as $r) {
if($r->shipping_number == "2326244" OR $r->shipping_number == "8451211"){
if($r->quarter == "1"){ echo "<td>$r->cost $<br />$r->qty</td>"; } else { echo "<td> </td>"; }
if($r->quarter == "2"){ echo "<td>$r->cost $<br />$r->qty</td>"; } else { echo "<td> </td>"; }
if($r->quarter == "3"){ echo "<td>$r->cost $<br />$r->qty</td>"; } else { echo "<td> </td>"; }
if($r->quarter == "4"){ echo "<td>$r->cost $<br />$r->qty</td>"; } else { echo "<td> </td>"; }
}
}
echo "</tr>";
除此之外,显然foreach
循环遍历结果两次,导致不创建4个单元格,但是8。
如何在一行上输出它,以便查询和格式化数据,使其仅通过一个循环运行它(或者如何从多个循环输出单行数据? )
我该怎么做?
请记住,我有多个可能适用于单个表的shipping_numbers(客户端),因此我需要将所有总计合并为一个结果,除了以季度(月等)分隔 - 但这些是分开的查询)。
答案 0 :(得分:-1)
您可以在不重写查询的情况下执行此类操作:
location
答案 1 :(得分:-1)
更改查询以选择每个季度实际上是一个不错的选择。
此查询中的if语句表示&#34;如果是x quarter,则获取由新行分隔的数量和成本,否则为0.&#34;
SELECT
IF(QUARTER(TIME) = 1, CONCAT(SUM(qty), '\n', SUM(COST)), 0) as q1,
IF(QUARTER(TIME) = 2, CONCAT(SUM(qty), '\n', SUM(COST)), 0) as q2,
IF(QUARTER(TIME) = 3, CONCAT(SUM(qty), '\n', SUM(COST)), 0) as q3,
IF(QUARTER(TIME) = 4, CONCAT(SUM(qty), '\n', SUM(COST)), 0) as q4,
shipping_number
FROM order_items
GROUP BY shipping_number, QUARTER(TIME)
ORDER BY shipping_number, QUARTER(TIME)
然后您必须更改回显线以适应查询更改。 nl2br
功能会将\n
从查询转换为您原始帖子中的<br>
。当季度没有结果时,它只会在单元格中放置一个0。
echo "<td>" . nl2br($r->q1) . "</td>";
echo "<td>" . nl2br($r->q2) . "</td>";
echo "<td>" . nl2br($r->q3) . "</td>";
echo "<td>" . nl2br($r->q4) . "</td>";
答案 2 :(得分:-1)
似乎这样的事情会起作用。
echo "<tr>";
echo '<th colspan="2" style="text-align: right !important; ">TOTAL QUEBEC - EASTERN CANADA</th>';
echo '<th>Amount<br />Quantity</th>';
$quarter = 1;
$it = 0;
$count = count($results);
$quarterPrinted = false;
while ($quarter <= 4) {
for ($i = $it; $i < $count; $i++) {
if ($results[$i]->quarter == $quarter
&& ($results[$i]->shipping_number == '2326244' || $results[$i]->shipping_number == '8451211')) {
echo "<td>{$results[$i]->cost} $<br />{$results[$i]->qty}</td>";
$it++;
$quarterPrinted = true;
break;
}
}
if (!$quarterPrinted) {
echo '<td> </td>';
}
$quarter++;
$quarterPrinted = false;
}
echo "</tr>";