0

On the table below how would I write a select clause for the SUM of prices for a particular year, say 2013? something like SUM(price WHEN year = 2012). And how would I refer to that result in PHP mysql_fetch_array().

+++++++++++++++++++++++++++++

Price | Date | Month | Year |

+++++++++++++++++++++++++++++

9.00  |343345|   2   | 2013 |

3.00  |343445|   2   | 2013 |

4.00  |343245|   1   | 2013 |

1.00  |342245|   1   | 2013 |

5.00  |333355|   12  | 2012 |
1
  • did you really separate a date in to multiple columns? 5 minutes i n the manual page for SELECT would probably answer the basics of this. Commented Mar 7, 2013 at 1:34

3 Answers 3

1

Use an alias:

SELECT SUM(price) AS my_sum 
WHERE year = 2102

Then in php:

$row = mysqli_fetch_assoc($result);
echo $row['my_sum'];
Sign up to request clarification or add additional context in comments.

1 Comment

SUM(price WHEN year = 2012) - unless I'm mistaken, that's not a valid expression
1

select sum(price) from table where year = 2012;

You would refer to it by using:

$data = mysql_fetch_array($query);
echo $data[0];

Comments

1

The query for this will be the below one:

select sum(price) as total_price from your_table_name where Year='2012';

And in PHP you can use it as:

$getTotal = mysql_query("select sum(price) as total_price from your_table_name where   Year='2012'");
while($resTotal = mysql_fetch_array($getTotal))
{
 $total = $resTotal['total_price'];
}

now you have the total in a variable $total

2 Comments

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
^^^^as true as it is, its getting a little tedious for regular S.O users to see it 10+ times a day

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.