I have a table on my php page populated with data from a MySQL query from a single table
The table looks like:
Location Jan Feb Mar etc… Total
Location1 5 13 7 25
Location2 10 10 6 26
Location3 22 1 7 29
Etc…
The ‘Total’ is calculated by the query using Sum ie SUM(IF(month = '1', 1,0)) AS 'jan', SUM(IF(month = '2', 1,0)) ASfeb, SUM(IF(month = '3', 1,0))
What I want are the totals for each column (Jan, Feb, Mar etc)
I can do this in PHP by adding the values as they are extracted but can I do it the query – and is there an advantage to doing so?
Thanks in advance for help rendered.
To me, this is a strange layout of a database, but I normally use a row based approach along these lines:
which makes totals and the like MUCH easier to perform.
However, given you structure, you could either continue to do what you are doing or use a little trickery. If you are doing more work with it in PHP (aside from just the totals) you could easily do a
concat()in SQL and get a preformatted string that is ready to beexplode()-ed into an array. From there you can use all the wonderful array functions in PHP to get totals or anything else you like.Edit: Righto, that makes some difference.
If you are using a normal row based approach to storing the data, you can probably make the database do all the work. If you need a query to get the individual months AND the totals, you can either do it in PHP of course, but you can also do a little trick like this:
This is handy if you have a DB that has loads of free CPU, but a webserver that is struggling or you have a very LARGE amount of data that needs to be tallied up for example. Just make the database do the crunching and return it as some specific number you can identify in your PHP code – months 1-12 will be normal, month 13 is the total.