2011-07-11 30 views
3

enter image description here產出增長

我想輸出20歲和19歲之間的百分比增長,我應該能夠說「高增長= 3」(通過採取高度178 - 175 )或者「身高增長= 0.017%」(178/175)。

我的代碼看起來像這樣

<table> 
    <thead><tr><td>Age</td><td>Height</td><td>Height Growth %</td><td>Weight</td></tr> </thead> 
    <tbody> 
<?php foreach ($healthdata->result_array() as $row) { 
     echo "<tr><td>".$row['age']."</td><td>".$row['height']."</td><td>%</td> <td>".$row['weight']."</td></tr>"; } ?> 
    </tbody></table> 

我的模型看起來像這樣

function display_healthdata() 
{ 
    $healthdata = $this->db->query("select * from healthdata where id = '1' order by age desc;"); 

    return $healthdata; 
} 

基本上我不知道我能做些什麼樣的SQL語句或者我需要寫什麼代碼能夠做出這些計算。我還認爲可能無法在數據庫或PHP中進行這種計算,而且我可能需要在客戶端而不是服務器端進行計算。

請讓我知道我可以/應該添加哪些其他信息,讓您更有幫助。


問題解決了 所以,人們發現這個代碼幫助...我用此問題的代碼是如下:

SELECT t1.*, (t1.height - IFNULL(t2.height, 0)) AS growth 
FROM healthdata AS t1 
LEFT JOIN healthdata AS t2 
ON (t2.age = (t1.age - 1)) 
where t1.id = '1' 
group by age 
+0

在我看來光強增長是1.7%,而不是0.017%:) – Karolis

回答

2

你可以用SQL連接來完成它......我太累了,實際上沒有給出正確的答案,但是這裏有一個類似於你的問題的鏈接。 = d

How to get difference between two rows for a column field?

EDIT

我要一個裂紋它。不保證不要炸燬你的房子;如上所述我很累;)

 
SELECT t1.*, (t1.height - IFNULL(t2.height, 0)) AS growth 
FROM healthdata AS t1 
LEFT JOIN healthdata AS t2 
ON (t2.age = (t1.age - 1))
+0

你搖滾!這真的有幫助! –

+0

=)沒問題。^_ ^ – Ryan

0

爲此,你需要插入一些邏輯到你的演講。我強烈建議不要這樣做。無論如何

<?php 

    $cache=array(); 
    foreach ($healthdata->result_array() as $row) { 
     echo "<tr>...</tr>"; 

     if ($row['age'] == 19) 
     $cache['19'] = $row['height']; 
     else if ($row['age'] == 20) 
     $cache['20'] = $row['height'];   
    } 

    $growth = $cache['20']-$cache['19']; 
    echo '<tr><td colspan="4">The growth is '.$growth.'</td></tr>'; 
?> 

小心這裏有2-3個不好的實踐,你不應該這樣做。