2011-04-29 94 views
0

我有一個結果集總和爲N情況和N不同的代碼在一段時間。雙鍵PHP總結到HTML表格

數據來源於此SQL

SELECT *, count(fldA) as ca 
FROM table 
WHERE ('... month/year ...') 
GROUP BY Sit, Cod 
ORDER BY count(fldA) DESC; 

確定這裏就是我想要的表格:

+--------------------------------+ 
| d/l | Sit. A | Sit. B | Sit. N | 
+-----+--------+--------+--------+ 
| c91 | 10 | 05 | 10 | 
+-----+--------+--------+--------+ 
| c93 | 15 |  |  | 
+-----+--------+--------+--------+ 
| cN. | 07 | 01 |  | 
+-----+--------+--------+--------+ 
| Tot | 22 | 06 | 10 | 
+--------------------------------+ 

所以相應的陣列(結果集)以上的表應該是這樣的:

SitA, C93, 15; 
SitN, c91, 10; 
SitA, c91, 10; 
SitA, CN., 07; 
SitB, c91, 05; 
SitB, cN., 01; 

請注意,一些情況(Collumns)和代碼(行)WIL L VARY。有些情況下,在結果集數組中,某些col x行組合應該沒有值。

顯然,總數應該在之後計算。

現在的問題是......這種結果集=>表創建的最好方法是什麼?最好只使用一個SQL請求。

THX

回答

0

所以,既然沒有任何幫助來... ...我做這個

<?php 

...

$sql=""; 

function timeFilter(){ 
    $q=""; 
    if ($_GET['mes']!='' || $_GET['ano']!=''){ $q.=" WHERE";} 
    if ($_GET['mes']!=''){ $q.=" MONTH(ouventrada)=$_GET[mes]";} 
    if ($_GET['mes']!='' && $_GET['ano']!=''){ $q.=" AND";} 
    if ($_GET['ano']!=''){$q.=" YEAR(ouventrada)=$_GET[ano]";} 
    return $q; 
} 

// we gonna use two buffers for collumns and rows... 

function fillBuff (&$buff, $fld){ 
    $buff = array(); 
    $sql = "SELECT $fld FROM ouv" . timeFilter() . " GROUP BY $fld"; 
    $res = mysql_query($sql); 
    while ($row=mysql_fetch_assoc($res)){ 
     $buff[]=$row[$fld]; 
    } 
} 

$quad .= "<div id='stats'>"; 

// Fill buffers 
$buffatc = array(); 
$bufftipo = array(); 
fillBuff ($buffatc, 'ouvatc'); 
fillBuff ($bufftipo, 'ouvtipo'); 

// Table headers 
$tbl = "<table class='resumo'>"; 
$tbl.= "<thead><tr><th></th>"; 
foreach ($bufftipo as $l){ 
    $tbl.="<th>$l</th>"; 
} 
$tbl.="</tr></thead>"; 

// Table foot (Totals) 
$tbl.="<tfoot><tr style='background-color: #f0f0f0'><td style='font-size: 50%;'>Total</td>"; 
foreach($bufftipo as $l){ 
    $sql="SELECT count(*) AS ca FROM ouv" . timeFilter(); 
    $sql.= (strpos($sql,"WHERE"))?" AND":" WHERE"; 
    $sql.=" ouvtipo='$l'"; 
    $rowt = mysql_fetch_assoc(mysql_query($sql)); 
    $tbl.="<td style='font-weight: bold'>$rowt[ca]</td>"; 
} 
$tbl.="</tfoot>"; 

// Table Body 
$tbl.="<tbody>"; 
foreach ($buffatc as $r){ //data 
    $tbl.="<tr>"; 
    $tbl.="<td style='font-size: 50%;'>$r</td>"; 
    foreach($bufftipo as $l){ 
     $sql="SELECT count(*) as ca FROM ouv " . timeFilter(); 
     $sql.= (strpos($sql,"WHERE"))?" AND":" WHERE"; 
     $sql.=" ouvatc='$r' AND ouvtipo='$l'"; 
     $rowt = mysql_fetch_assoc(mysql_query($sql)); 
     $tbl.="<td style='font-weight: bold'>$rowt[ca]</td>"; 
    } 
    $tbl.="</tr>"; 
} 
$tbl.="</tbody>"; 
$tbl .="</table>"; 

$quad.= $tbl; 

$quad.= "</div>"; 

我們throught爲collumns兩個 '緩衝區' 互動以及設置sql的行以一次計算每個單元格...

gl,thx

Paulo Bueno。