I have a table like following:
id q_id value
------------------------
1 2 5
2 2 NULL
3 2 5
4 2 NULL
5 4 2
6 4 NULL
7 4 2
8 4 NULL
What I want is to get the sum of (for example) all value where q_id = 2
$sq = mysql_query("SELECT SUM(value) AS sum FROM table WHERE q_id = 2)or die(mysql_error());
while($row = mysql_fetch_array($sq)){
$sum = $row['sum'];
}
echo $sum."<br>";
But I'm getting
5
5
But what I want is the sum of the value and expecting 10 instead.
Thank you for helping.
If you're going to loop over the result set anyway, why not just use
SELECT value FROM table WHERE q_id=2
then sum up those values using the while loop? Something like:
while($row = mysql_fetch_array($sq)) {
$sum += $row['value'];
}
echo $sum."<br>";
Edit: also, as Jason McCreary said above, you should look into an alternate method of querying the database. I would suggest searching php.net for "PDO", which is very easy to use.
We can directly sum in the query like
SELECT 5+6 AS addition
Give it a try... You are displaying value, there was missing quote in your code.
$sq = mysql_query("SELECT SUM(value) AS sum FROM `table` WHERE `q_id` = '2'")or die(mysql_error());
while($row = mysql_fetch_assoc($sq))
{
$sum = $row["sum"];
}
echo $sum . "<br>";
$sq="SELECT value FROM table WHERE q_id='".$am."'";
$result=mysqli_query($link,$sq);
while($row=mysqli_fetch_assoc($result)) {
$sum += $row['value'];
}
echo "<p>Sum: ".$sum."</p><br>";
//$am ='2';
//$link -- connection to the data base
Please put $am ='2'; before the select statement and also make sure you have connected to the data base using $link
You will get the total sum according to the value of q_id
I have tested the code and works fine.
You need to add a GROUP BY to your query. Add the following to the end
GROUP BY q_id
Related
I have one table with some rows and lot of columns (about 50)
- I don't want to list all the column names, co I use a while loop to go through the table and a foreach command to find the column names and values.
Now I would like to add these two rows into one row (where id is 1) and sum the values together...
id | col 1 | col 2 | ...
1 30 21
1 11 16
2 75 0
It should look like this
id | col1 | col2 | ...
1 41 37
2 75 0
This is what I have...
$query = mysql_query("SELECT * FROM `table` WHERE `id`='1'");
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $key => $val) {
if($key != 'id') {
//the sum code...?
}
}
}
Could you please help me? Thank you a lot...
Based on your code which indicates you're using mysql I'm going to give you a mysql solution (which can easily be ported to most RDBMS). What you're looking for can easily be accomplished with aggregate functions. Follow the link to read about all the aggregate functions mysql has.
SELECT id, SUM(col1), SUM(col2) FROM table GROUP BY id;
just sum the results in mysql.. databases are made to handle things like this so it'll be a faster solution than doing it just in php.
SELECT
id,
SUM(col1),
SUM(col2)
FROM table
GROUP BY id;
Try this: See the Explanation as comments:
<?php
$query = mysql_query("SELECT * FROM `table` WHERE `id`='1'");
//Initially Set all the columns as zero.
$col1 = 0; $col2 = 0;
//Etc.
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $key => $val) {
if($key != 'id') {
$$key += $val;
//Like: $col1 += 30;
}
}
}
//Now All the variables are ready added:
//Like: $col1 = 41;
//Like: $col2 = 37;
//Use them However you like:
//To update:
//1. First Delete both rows:
$query = mysql_query("DELETE FROM `table` WHERE `id`='1'");
//2. Insert
$query = mysql_query("INSERT INTO `table` (`id`,`col1`,`col2`) VALUES ('1','{$col1}','{$col2}') ");
//And so on
?>
I have a small query that sums the totals of columns, is there a way I can ORDER BY ASC so that the result displays the rows with the biggest total first.
My query is:
select
sum(SeqID0101 = 1) as SeqID0101,
sum(SeqID0102 = 1) as SeqID0102,
sum(SeqID0103 = 1) as SeqID0103,
sum(SeqID0104 = 1) as SeqID0104,
sum(SeqID0105 = 1) as SeqID0105,
sum(SeqID0106 = 1) as SeqID0106,
sum(SeqID0107 = 1) as SeqID0107,
sum(SeqID0108 = 1) as SeqID0108,
sum(SeqID0109 = 1) as SeqID0109,
sum(SeqID0110 = 1) as SeqID0110
from
PH001_Hist
EDIT
Hi and thanks for your replies.
I am using the code below to produce tow columns, 1 with the name of the field, 2 with the data content. This works as I require. But when the query sums the content of the fields I need to order the result to display the largest field content first.
Example:
Fieldname FieldData
SEQID0101 - 8
SeqID0108 - 6
SeqID0103 - 2
and so no.
$row = mysql_fetch_assoc($FailedList);
echo '<table>';
foreach ($row as $k => $v)
echo '<tr><td>'.$k.'</td><td >'.$v.'</td></tr>';
echo '</table>';
I just can't get the code right to produce the require result.
Any help would be great.
Try that:
ORDER BY GREATEST(SeqID0101,SeqID0102,SeqID0103,SeqID0104 , .....) DESC
I'm trying to do 2 things.
1) Get the amount of rows in this query
SELECT
COUNT(*)
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
As you can see that is no problem ^^
2) Determine the number within the range of rows that is returned by id
Ex: ID 765 is Item 4 of 7 where column_1 = 152 and column_3 = 42
Does anyone have any basic solutions to this problem with almost pure MySQL? I'd like to avoid iterating through all the rows and setup a counter to increment until it matches current id like this:
$sql = '
SELECT
*
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
';
$query = mysqli_query($sql);
$current_id = 2523;
$i = 1;
while ($row = mysqli_fetch_assoc($query)) {
if ($row['id'] == $current_id) {
$current_position = $i;
}
$i++;
}
print 'Current position in range is: '. $current_position;
Also please don't worry about the actual syntax, I won't be using this exact script, but you get the logic that I'd like to avoid using. If anyone has a better solution, please let me know. Thanks in advance!!
I have a database like this:
ID | AMOUNT
1 15.00
2 100.00
3 100.00
I need to add all the amounts together. I have tried some PHP math stuff but just can't make it work.
<?php
$total = mysql_query("SELECT amount FROM payments")
or die(mysql_error());
$grandtotal=
while($total1 = mysql_fetch_array( $total )) {
$total1['amount']+
};
?>
SELECT SUM(amount) as sum_amount FROM payments
There are two solutions for the specific task you're trying to accomplish:
while($total1 = mysql_fetch_array( $total )) {
$total1['amount']++; //returns Returns $total1['amount'], then increments it by one.
} // <-- semicolon removed
As Mark Baker suggested in comments, you could do it from within your SQL query using SUM:
SELECT SUM(amount) AS amount_sum FROM payments
I have an issue with my code. I have 2 tables. First employee_id:
|Employee id|
1
2
3
And the second table called employee_times:
|Employee_id|Hours_dev|hours_pm|
|1|2|3|
|1|3|4|
|2|3|3|
What I am trying to do is to calculate the total time that each employee has worked (hours_dev+hours_pm). For example employee_id 1 has worked 12 hours
So far I have tried to retrieve all the employee_id from the first table and use a for loop to go through the employee_times in an SQL statement (SEE CODE BELOW). However the code does not work as it prints 0 for both employee_id and total_hours.
I am using MYSQL on a localhost server.
$sql = "SELECT employee_id FROM employee";
$result = mysql_query($sql);
while($row = mysql_fetch_array)
{
$employee_id = $row['employee_id'];
}
$employee_id_length = sizeof($employee_id);
for($i = 0; $i < $employee_id_length; $i++)
{
$sql4 = "SELECT employee_id, hours_dev, hours_pm FROM employee_times WHERE employee_id= '$employee_id[$i]'";
$result = mysql_query($sql4);
while($info = mysql_fetch_array($result));
{
$employee_id = $info['employee_id'];
$hours_dev=$info['hours_dev'];
$hours_pm=$info['hours_pm'];
$total_hours = ($total_hours + $hours_dev + $hours_pm );
}
//print "$employee_id worked for $total_hours";
}
Any help is much appreciated.
you can get sum directly
select employee_id, sum(hours_dev)+ sum(hours_pm) as total
from employee_times WHERE employee_id= '1'
group by employee_id
refer this Fiddle Demo
this should get the data you need
SELECT
hours_dev,
hours_pm,
sum(hours_dev) + sum(hours_pm) as total_hours
FROM
employee_times
WHERE
employee_id = 123
GROUP BY
employee_id
Take a look at aggregate functions:
http://www.w3schools.com/sql/sql_functions.asp
http://www.w3schools.com/sql/sql_func_sum.asp
This SQL query should pull the info much quicker than by script;
SELECT Employee_id, SUM(Hours_dev), SUM(Hours_pm), SUM(Hours_dev + Hours_pm)
FROM employee_times
GROUP BY Employee_id