Column Calculator - php

I have the following table and want to know how to set up a column total to calculate the sum of the row. I want the total column to calculate first_bid - second_bid.
id | First Bid | Second Bid | Total
0 | 7 | 1 | (first_bid)-(second_bid)
1 | 8 | 2 |
2 | 5 | 3 |
3 | 4 | 4 |
4 | 5 | 5 |
5 | 5 | 6 |
I need to display to the user all previous bids and total on a page. The total should be in descending order also.

SELECT id, First_Bid, Second_Bid, First_Bid - Second_Bid AS Total
For the grand total, you'd have to run a second query with SUM() aggregate functions. Which is somewhat redundant, since you can just do the summation in your client as you retrieve the data. e.g.
$total = 0;
while($row = fetch_from_db($result)) {
$total += $result['Total'];
... display row data ...
}
... display total ...

You can just calculate the total when you are querying the database.
SELECT first_bid, second_bid, (first_bid - second_bid) as total FROM table ORDER BY 3 DESC
Something along these lines

Try this query:
SELECT *, (First Bid-Second Bid) as total from TABLE

Related

Sum with WHERE and GROUP BY CLAUSE

Good day. I am really in big trouble as I can't figure what is wrong with my statement. It is as follows:
$sumitem = mysqli_query($conn,"SELECT SUM(AMOUNT) AS TOTAL FROM sum_query WHERE MAIN_ID = 1 GROUP BY ITEM_ID");
$sum = mysqli_fetch_assoc($sumitem);
I am trying to print $sum['TOTAL'] but what it shows the first column only. Below is my sample table:
MAIN_ID | ITEM_ID | AMOUNT | DESC | OTHER_DETAILS
1 | 1 | 500 | Item 1 | a
1 | 2 | 5000 | Item 2 | a
1 | 2 | 5000 | Item 2 | b
My desired result should be 5500 but it only returns 500.
Thank you very much.
If you want ans as 6500 then remove group by clause
SELECT SUM(AMOUNT) AS TOTAL FROM sum_query WHERE MAIN_ID = 1
SELECT SUM(g.AMOUNT) AS TOTAL
FROM sum_query g
WHERE g.MAIN_ID = 1
GROUP BY g.ITEM_ID
This query is working plase try out this
You are having 2 records for Item 2. and i don't know why you are keeping 'a and b' in OTHER_DETAILS.
Your requirement is not clear
If you want to take only the records matching with OTHER_DETAILS 'a',then use the following query
SELECT SUM(AMOUNT) AS TOTAL FROM sum_query WHERE MAIN_ID = 1 and OTHER_DETAILS = 'a'

PHP MySql: Loop check row value if same as previous, add something at the last item of the group

Hello I need some help in grouping items. I have data like below.
id | area | cost
1 | a | 100
2 | b | 100
3 | a | 100
4 | c | 100
5 | c | 100
6 | a | 100
I want to achieve to display a table like below
id | area
1 | a
3 | a
6 | a
display total (sum of all area a)
2 | b
display total (sum of all area b)
4 | c
5 | c
display total (sum of all area c)
I can segregate all the rows order by area(asc) and arrange it by id(desc)
I am using the code below but doesnt do what I intended to do.
$itemdeleted = 1;
$query = $conn->prepare('
SELECT *
FROM projectscostbreakdown
WHERE projectscostbreakdown_projectid=:projectsid
&& projectscostbreakdown_deleted=:itemdeleted
GROUP
BY projectscostbreakdown_areaname ASC
, projectscostbreakdown_id DESC
');
$query->bindParam(':projectsid', $projectsid, PDO::PARAM_INT);
$query->bindParam(':itemdeleted', $itemdeleted, PDO::PARAM_INT);
$query->execute();
Then loop it
foreach ($query as $row) {
display id - area - cost
if (currentareavalue != previousareavalue)
display sum of all the previous costs with the same areaname
}
My problem is i want to display the total cost of every area at the end of the last entry of an area.
I am new to php and please bear with me.

MySQL Select second count of pre selected results

Hello I am trying to make a Select where the uses chooses department and would like to have clause WHERE this department is first, let's say we select 10 results from department: Taxes and then make a SUM SELECT of fee WHERE status = 1. Which results be selected based on the first select All the results are coming from the same table.
| id | department | status | fee |
----------------------------------
| 1 | tax | 1 | 20 |
| 2 | tax | 2 | 20 |
| 3 | tax | 1 | 20 |
| 4 | accounting | 1 | 20 |
So I would like to select if department is choose as tax, and status is 1 the sum of FEE columns which should be 40
So far my Select query looks like this:
SELECT P.id, P.fee, (SELECT SUM(P.fee) FROM cases P WHERE status = 1) as fee_USD
FROM cases P WHERE 1";
if (!empty($department)) { $sql .= " AND P.department = '$department'"; }
the last line is checking if department is given as select option. there are other options as well but to make it simple I have pasted only this part of it. Any help is welcome.
In the Current Selection Fee is = 80
You have to add correlation to your query:
SELECT P1.id, P1.fee,
(SELECT SUM(P2.fee)
FROM cases P2
WHERE P2.department = P1.department AND status = 1) as fee_USD
FROM cases P1
WHERE 1 ...
This way the subquery will return the SUM of only those records which are related to the current record of the main query.

Display only first of duplicate column values

How to query for erase the view below?
+-------------------+------------+
| Order_id | Weight |
| 20 | 4 |
| 21 | 5 |
| 22 | 2 |
| 22 | 2 |
+-------------------+------------+
To be like this:
+-------------------+------------+
| Order_id | Weight |
| 20 | 4 |
| 21 | 5 |
| 22 | 2 |
| 22 | |
+-------------------+------------+
When displaying results but not entered into the database.
A simple way is:
select DISTINCT order_id, weight from xyz
UNION
select order_id, null from xyz
group by order_id, weight
having count(*) > 1
Order by weight desc;
The 1st select statement will display all the unique values and 2nd one will retrieve only the repeated values.
In your required output table, it seems like you want to display all the non-repeated rows and the 1st column value of repeated rows but not 2nd column value. The above query will allow you to do that.
OK, here is how to do it:
SELECT
Order_id,
Weight,
if(#order_id = Order_id, '', Weight) as no_dup_weight,
#order_id := Order_id as dummy
FROM Table1
ORDER BY Order_id asc;
You basically need to check to see if the previous Order_id is the same as the current, and if they are, output an empty field.
Here is an SQLFiddle demonstrating the solution.
Do you actually need 2 rows for the dupes? Can't you just use the DISTINCT clause as per http://www.mysqltutorial.org/mysql-distinct.aspx
Or is it important to know what has duplicates. In which case you should look into the GROUP BY clause

Update value of row in mysql with conditions?

I want to achieve something like this using php and mysql
if the customer has an account with rewards and wants to spend rewards, how do i update the table so that it will going to subtract the spent reward to the table.
Definitely it will going to get the sum of reward by customer_id then subtract the spent reward. IF the first row(reward) is less than the spent value, it will going to subtract all then go to next row get the difference from previous result until the value of spent is equal to 0.
sample:
spent = 60
id_customer = 2
I have a table like this
id | id_customer | reward
1 | 2 | 50
2 | 2 | 20
3 | 3 | 100
4 | 4 | 5
the result should be something like this:
1st row: 50(value of first row) - 60 = 0 (with remaining 10)
2nd row: 20(value of 2nd row) - 10 (remaining points from first row) = 0
id | id_customer | reward
1 | 2 | 0
2 | 2 | 10
3 | 3 | 100
4 | 4 | 5
Hope that makes sense. Thanks
This is the logic of my solution (of course, maybe more than this one and a better ones):
Get the set of rows for that customer (id_customer = 2) and loop through the rows returned.
In each iteration, compare the value of field reward against the amount you like to subtract (60).
If the actual value is >= 60, update that row and exit. If not, update it with 0, update the remain value (60 - row value) and go to the next item in the iteration doing the same action.
In MySQL, I think the best way to do this is with variables. This should work:
declare #spent := 60;
update tablelikethis
set reward = (case when #spent = 0 then reward
when #spent >= reward
then (case when (#tmp := #spent) is null then NULL
when (#spent := #spent - reward) is null then NULL
else 0
end)
else (case when (#tmp := #spent) is null then NULL
when (#spent := 0) is null then NULL
else reward - #tmp
end)
end)
where id_customer = 2
order by id;
MySQL makes this a little hard to do in a single update, because you cannot use order by with a join. The variable version just has to deal with logic on whether the amount remaining for the reward is bigger or less than the amount remaining being spent.
I'd structure your database in a different way. You could create a column called "reward_points" in the customer table, and have a separate reward table. The structure is:
REWARD_TABLE
----------------------------------
reward_id | customer_id | reward
----------------------------------
1 | 2 | 50
2 | 2 | 20
3 | 3 | 100
4 | 4 | 5
CUSTOMER_TABLE
-------------------------------------------------
customer_id | name | reward_points
-------------------------------------------------
1 | Eddard Stark | 0
2 | Jaime Lannister | 70
3 | Joffrey Baratheon | 100
4 | Theon Greyjoy | 5
Then you could just update the CUSTOMER_TABLE with the new value. You could keep the REWARD_TABLE as a 'reward history'. Even better... upon purchase, you could add a negative transaction to the REWARD_TABLE, so when you would do a SELECT SUM(reward) asRewardFROM reward_table WHERE customer_id = 2 GROUP BY customer_id, it would count all the negative transactions as well, resulting in something, which is close to your concept.

Categories