Selecting only amount with values greater than 0 in sql - php

I have this table
The table contains amount with values that has both negative and positive signs. I was able to fetched the sum of positive amount but after the sumation I have zero values which I don't want to show - it fetched all values.
Objective: fetch sum of amount and return amount with no zero values.
What I tried so far
$ques = "select * from company";
$checks22y = sqlsrv_query($conn, $ques);
$row22y = sqlsrv_fetch_array($checks22y, SQLSRV_FETCH_ASSOC);
$daty = $row22y['BRSES_DATE']->format('Y-m-d H:m:i');
$com = $row22y['branch'];
$query = "SELECT distinct ".$limitresult." Member.Branch,Member.GL_No,Member.Ac_NO,Member.BRANCH+Member.GL_NO+Member.AC_NO
AS BRGLAC,Customer.Cust_No,Customer.Name,Group_Name,ID_CARD,Subgroup as subgroup2,
Cust_Type,Cust_Sex,Cust_Cat,Area_Code,Cust_Type,Dobirth,Address,Ref_No,Bank_VNO,Cust_Ca2,
nType,Group_Code FROM Member INNER JOIN CUSTACC ON Member.Branch = CustAcc.Branch AND
Member.GL_NO = CustACC.GL_No AND Member.AC_NO = CustACC.AC_No
INNER JOIN Customer ON Member.Branch = Customer.Branch ".$branchid." AND Member.Cust_No = Customer.Cust_No ".$accnos." WHERE
CUSTACC.Exp_Date < '$daty' AND MEMBER.Gl_NO IN (SELECT Coa.GL_NO FROM Coa WHERE Product = 'S' ) AND cust_type IN ('IND','GRP','MEM') ";
$check = sqlsrv_query($conn, $query);
$i = 1;
while($rows = #sqlsrv_fetch_array( $check, SQLSRV_FETCH_ASSOC)) {
$ac = $rows['Ac_NO'];
$br = $rows['Branch'];
//Second sub query
$get ="select ac_no, gl_no, SUM(amount) as OutBalance,MAX(Batch_Date) AS Last_Trx2 from memtrans where gl_no like '2001%'
and ac_no='$ac' group by ac_no, gl_no HAVING SUM(amount) > 0
";
$check2 = sqlsrv_query($conn, $get);
$rowb = sqlsrv_fetch_array( $check2, SQLSRV_FETCH_ASSOC);
//Third sub query, OD history
$od = "select od_limit from custacc where ac_no='$ac' and od_limit > '0'";
$odc = sqlsrv_query($conn, $od);
$rowbo = sqlsrv_fetch_array( $odc, SQLSRV_FETCH_ASSOC);
}
The outcome
If you look at the Outstanding Balance you will see zero values appearing.
The secon sub query is where the fetching of Outstanding Balance took place.

Just solved it.
Here is the query I later used:
SELECT distinct ".$limitresult." member.Branch,Member.GL_No,Member.Ac_NO,Member.BRANCH+Member.GL_NO+Member.AC_NO
AS BRGLAC,Customer.Cust_No,Customer.Name,Group_Name,ID_CARD,Subgroup as subgroup2,Cust_Type,Cust_Sex,Cust_Cat,Area_Code,Cust_Type,Dobirth,Address,Ref_No,Bank_VNO,Cust_Ca2,nType,Group_Code, SUM(memtrans.amount) as OutBalance,MAX(memtrans.Batch_Date) AS Last_Trx2,company.BRSES_DATE, company.branch, CustACC.od_limit FROM Member INNER JOIN CUSTACC ON Member.Branch = CustAcc.Branch AND Member.GL_NO = CustACC.GL_No AND Member.AC_NO = CustACC.AC_No INNER JOIN Customer ON Member.Branch = Customer.Branch AND Member.Cust_No = Customer.Cust_No INNER JOIN memtrans ON memtrans.ac_no = member.ac_no INNER JOIN company ON company.branch = member.branch ".$branchid." ".$accnos." WHERE CUSTACC.Exp_Date < company.BRSES_DATE AND CUSTACC.od_limit > '0.00' AND MEMBER.Gl_NO IN (SELECT Coa.GL_NO FROM Coa WHERE Product = 'S' ) AND cust_type IN ('IND','GRP','MEM') group by memtrans.ac_no, memtrans.gl_no,company.branch, member.branch, member.gl_no,Member.ac_no,
Customer.cust_no, Customer.name, Customer.group_name,Customer.id_card,Customer.subgroup,Customer.cust_type,
Customer.cust_sex, Customer.cust_cat,Customer.area_code,Customer.dobirth,Customer.address,Customer.ref_no, Customer.Bank_VNO,Customer.cust_ca2,Customer.ntype,Customer.group_code,company.BRSES_DATE,CUSTACC.od_limit HAVING SUM(memtrans.amount) > 0)
Thanks guys. From a grateful heart.

Related

I get a NULL value from var_dump when assigning a variable to an array in my select query

I have written a SELECT Query to concatenate a person's name and email address. I then want to echo this string.
Here is the code:
$sqldiv = "Select concat(p1.display_name, " - ", p1.user_email) AS Contact FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
If I use this SELECT QUERY it works:
$sqldiv = "Select p1.display_name FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
The only difference is that I am using concat. If I run the SELECT Query through SQL I get the output in a single string, which I assume is correct to set $div as an array.
What am I doing wrong?

How to join 4 tables "many to one" correctly, in sql?

good morning. I need to create a query that joins me 4 tables: recipes, food_recipes, prices_food AND users
tables
Currently what I do is:
search for recipes together with their user
inside I look for information on their food
and inside, in each iteration, I look for the information on the price of the food that the user entered
If the user did not enter any price, I look for the average of all the prices of people in the same country on certain dates
If the number of people who entered that price does not exceed the minimum, then the total price of the prescription will be 0
and it works very well. But I need everything to be in the same query to be able to filter for the price.
Try to create the query, with inner join and left join, but either way I don't get the result I need. Could you give me some guidance on what the correct syntax would be like? please
$wsqli="SELECT * from recipes
INNER JOIN users
on recipes.id_user = users.id_user
where $where
order by recipes.date desc
limit $limit
OFFSET $offset ";
$result = $linki->query($wsqli);
if($linki->errno) die($linki->error);
while($row = $result->fetch_array()){
$precio_receta = recipe_price($id_recipe);
}
function recipe_price($id_recipe)
{
$current_date = date('Y/m/d', strtotime('+1 day'));
$previous_date = date('Y/m/d', strtotime('-8 month'));
$price_recipe = 0;
$wsqli="SELECT * from recipes_foods
where id_recipe='$id_recipe' ";
$result = $linki->query($wsqli);
if($linki->errno) die($linki->error);
while($row = $result->fetch_array()){
$weight = $row['weight'];
$fdcId = $row['fdcId'];
$wsqli="SELECT * from foods_prices
where fdcId='$fdcId' and id_user='$id_user_session' and (foods_prices.date between '$previous_date' and '$current_date')";
$result2 = $linki->query($wsqli);
if($linki->errno) die($linki->error);
if($row = $result2->fetch_array()){
$price_recipe = $price_recipe + (($row['price'] / 1000) * $weight);
}else{
$wsqli="SELECT
COUNT(*) as quantity_prices,
AVG(price) as average_price
from foods_prices
inner join users
on users.id_user = foods_prices.id_user
where fdcId='$fdcId'
and country='$user_country'
and (foods_prices.date between '$previous_date' and '$current_date')";
$result2 = $linki->query($wsqli);
if($linki->errno) die($linki->error);
if($row = $result2->fetch_array()){
if ($row['quantity_prices'] > 50) {
$price_recipe = $price_recipe + (($row['average_price'] / 1000) * $weight);
}else{
$price_recipe = 0;
return $price_recipe;
break;
}
}else{
$price_recipe = 0;
return $price_recipe;
break;
}
}
}
return $price_recipe;
}
I have already managed to gather all the data in a single query.
$wsqli="SELECT *
from recipes
left JOIN recipes_foods
on recipes_foods.id_recipe = recipes.id_recipe
left JOIN foods_prices
on foods_prices.fdcId = recipes_foods.fdcId
left JOIN users
on users.id_user = foods_prices.id_user
where country='AR'
order by recipes.date desc";
$result = $linki->query($wsqli);
if($linki->errno) die($linki->error);
while($row = $result->fetch_array()){
var_dump($row);
}
but I still can't:
know if the quantity of prices entered for that food is greater than or equal to that required (min. 50). Try "where COUNT (price)> 50" but it says "Invalid use of group function"
If the quantity of prices IS LESS than required, stop last in the results (or do not show)
If the quantity of prices is greater than required .... Order by price. Adding "order by COUNT (price) desc" reduces the results obtaining only the first one.

Get highest sum value from two tables

Here is my code:
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
<tr> <?php echo $sum; ?></tr>
}while($row_query1 = mysql_fech_assoc($result));
I need to get the highest value of $sum from this loop. Can anyone help?
You can do like this.. take a temporary variable($temp) which can have check upon the sum variable($sum).
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
$temp = 0;
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
if($temp < $sum)
$temp = sum;
echo "<tr>$sum</tr>";
}while($row_query1 = mysql_fech_assoc($result));
echo "maximum sum :".$temp;
I would advice doing a JOIN instead of performing the sub queries yourself:
select user, sum(column) + sum(column1) as total
from table1
INNER JOIN table2 ON names = user
GROUP BY user
The rest should be straightforward in code.

help with a query

i have a function where i get the ratings of the selected user by id,
it gets the ratings from one type of things, the ratings of a diff type of things and then does a+b
i know it's not very optimized but i'm focus on making all work...
this i do it like this
function votos_usuario($id){
$previa = "SELECT id FROM preguntas WHERE id_usuario = '$id'";
$r_previo = mysql_query($previa);
$ids_p = '0, ';
while($items_previos = mysql_fetch_array($r_previo)){
$ids_p .= $items_previos['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_p,0,-2);
//echo $ids;
$consulta = "SELECT valor FROM votos_pregunta WHERE id_pregunta IN ( $ids )";
//echo $consulta;
$resultado = mysql_query($consulta);
$votos_preguntas = 0;
while($voto = mysql_fetch_array($resultado)){
$votos_preguntas = $votos_preguntas + $voto['valor'];
}
//$votos_preguntas= 0;
//$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");
$previa_r = "SELECT id FROM recetas WHERE id_usuario = '$id'";
$r_previo_r = mysql_query($previa_r);
$ids_r = '0, ';
while($items_previos_r = mysql_fetch_array($r_previo_r)){
$ids_r .= $items_previos_r['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_r,0,-2);
$consulta_b = "SELECT valor FROM votos_receta WHERE id_receta IN ( $ids )";
//echo $consulta;
$resultado_b = mysql_query($consulta_b);
$votos_recetas = 0;
while($voto_r = mysql_fetch_array($resultado_b)){
$votos_recetas = $votos_recetas + $voto_r['valor'];
}
$total = $votos_preguntas + $votos_recetas;
return $total;
}
Now the Question,
how can i do it to get all users ordered by rating desc ???? i just can't see it :S
SELECT uid, SUM(Votes)
FROM (
SELECT p.id_usuario uid, SUM(vp.valor) votes
FROM preguntas p JOIN votos_pregunta vp ON p.id = vp.id_pregunta
GROUP BY p.id_usuario
UNION ALL
SELECT r.id_usuario uid, SUM(vr.valor) votes
FROM recetas r JOIN votos_receta vr ON r.id = vr.id_receta
GROUP BY r.id_usuario
) rs
GROUP BY uid
ORDER BY SUM(Votes) DESC
instead of your php loop and all the sub queries, you can use this single query to get what you want:
SELECT (
SELECT SUM(vp.valor)
FROM preguntas p JOIN votos_pregunta vp ON p.id = vp.id_pregunta
WHERE p.id_usuario = '$id')
+ (
SELECT SUM(vr.valor)
FROM recetas r JOIN votos_receta vr ON r.id = vr.id_receta
WHERE r.id_usuario = '$id'
)
Also, when you're only using the associative keys in the result array, using mysql_fetch_assoc() is much, much faster than mysql_fetch_array().
Same applies to using mysql_fetch_row() instead when you're just using the numerical keys.

PHP coding question

How can I grab the count value from the query MySQL query below using PHP.
Here is My MySQL code.
$dbc = mysqli_query($mysqli,"SELECT COUNT(*) FROM((SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1')
UNION
(SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.friend_id = users.user_id
WHERE users_friends.friend_id = 1
AND users_friends.friendship_status = '1')) as friends");
using SQL_CALC_FOUND_ROWS should simplify things:
$dbc = mysqli_query($mysqli,"SELECT SQL_CALC_FOUND_ROWS users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1'
");
then afterwards do
$rs = mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$rec = $rs->fetch_array();
$count = $rec[0];
This method will return the number of records that match the query, ignoring any LIMIT statement, whereas using $rs->num_rows will only give you the number of records actually returned. Depends which one you want.
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
http://us.php.net/manual/en/mysqli.query.php
Assuming that you are correctly connected to the MySQL server and your query are executed correctly, you can use the following code:
$values = mysql_fetch_row($dbc);
$count = $values[0];
Your query should look like SELECT COUNT(*) as numThings FROM xxx
The numThings is what you will reference in PHP:
$result = mysql_query("SELECT COUNT(*) as `numThings` FROM xxx");
$row = mysql_fetch_assoc($result);
$count = $row['numThings'];

Categories