Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output Growth between Numeric Datafields in database

Tags:

sql

php

enter image description here

I would like to output the growth percentage between age 20 and age 19. I should be able to say "Height Growth = 3" (By taking the height 178 - 175) or that there was a "Height Growth = .017%" (178/175).

My code looks like this

    <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>

My model looks like this

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

   return $healthdata;
}

Essentially I don't know what kind of SQL statement I can do or what code I need to write to be able to make these calculations. I also thought that it may not be possible to do this calculation on the database or in PHP and that I may need to do it on the client side instead of the server side.

Please let me know what other information I can/should add for you to be more helpful.


PROBLEM SOLVED So that people finding this code are helped... The code I used for this issue was the following:

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
like image 327
Pascal Wagner Avatar asked Jun 24 '26 20:06

Pascal Wagner


1 Answers

You can do it with SQL joins... I'm too tired to actually give a proper answer, but here's a link to a problem that seems similar to yours. =D

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

EDIT

I'll take a crack at it. NOT guaranteed to not blow up your house; as stated I'm very tired ;)

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))
like image 96
blitzmann Avatar answered Jun 27 '26 09:06

blitzmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!