php/mysql add rows together to get total - php

here's the scenario. I am generating a report of all the members who have dues to pay for a certain time period.
I am successfully selecting and displaying each database entry as a row in a html table.
The problem is the total fields the report must have. Each member pays different amounts based on what services they use, so I must add the values in each field individually to ensure proper result.
Question is, how do I go about adding the rows/field together?
Edit:
To clarify. I am adding dues paid and donations paid fields. They are classified and integer in mysql database.
Example, let's say that my query returns 3 results. I wish to add the dues paid for all 3 results and display it as total_dues_paid. Same idea for donations.
This must be dynamic for any given number of results, as this changes month to month and we have seen several hundred results in some months.
Thanks

To add fields (columns):
SELECT col1, col2, col3, (col1+col2+col3) AS Total FROM table;
To add rows together, use the SUM() aggregate:
SELECT
userid,
SUM(col1) AS col1_total,
SUM(col2) AS col2_total
FROM table
GROUP BY userid

You can add in your query string.
SELECT (field1 + field2) AS Total
FROM table

Related

Copy rows in MySQL table multiple times and adding additional column

I have created MySQL table in database. Table name is products and the columns are( prodict_id(pk) product_name and pack_size) as shown in the figure below.
What I want to do is , copy all the rows in the table and add additional information in additional column called (buyer_name) so each product is associated with a specific buyer which makes it unique
Is there a way I can achieve this using query? Where I can give a list of buyers and it attaches it to all rows in table?
p.s I have almost 700 rows in my table and I have 12 buyers, so if I do it manually, it will consume too much time
As per your comment your buyer details are in a table and you want to map each product with each of the buyer then you can write your insert query like below:
insert into newtable
select t1.*, t2.buyername from products t1 join buyers t2
DEMO
You can use where clause also to filter some results from either of the table.
It seems you want to automate the data insertion from product table to buyer table. How about, if you select that fetches all the buyers first and then you insert into buyer table.
It can be based on subquery where insert is the outer one and select is the nested one.
Good luck !

PHP/SQL: Prevent Option values from repeating

So I am trying to create a query that shows the list of all the dates customers came in to order food. However, since there were multiple customers for a particular day and thats how the values have been stored in the table, whenever I turn the following query:-
SELECT DateOfEntry FROM KFC;
Although it works and I see all the details, I dont want the same date value to repeat. For example if Two customers A and B, came in on 11/11/17 to order food, I would get the result of the above mentioned query with two records of same date. I dont want the same dates to repeat. What do I do?
I know DISTINCT works but the problem is, I am creating a php page where admins can check the list of all the users who came in on a particular day. So I am using the select and option methods of HTML to select a date which then shows the list of the users who made an entry that day. With this code, only one record is shown
Try:
SELECT DISTINCT DateOfEntry FROM KFC;
Try :
SELECT DISTINCT DateOfEntry FROM KFC;
or this
SELECT DateOfEntry FROM KFC
GROUP BY DateOfEntry;

Quicker way to sum sections of an SQL column

Say I have a table with 1million rows. One column lists the "Group", and another lists "Sales". The Group #'s range from 1 to 100,000 such that each Group has about 10 Sales entries. I want to somehow summarize the data into 100,000 rows with the sum of Sales for each group rather than each individual sale.
My method so far has been to run a PHP loop from 1 to 100,000 where each iteration sends an SQL query to sum(Sales) WHERE Group=$i. Then I can either echo it into an html table, or insert it into a new SQL table. Problem is it takes hours this method.
Any tips on how I can improve this process? Is there a way to write this as a single SQL query that will massively increase speed? Thanks
Just try a GROUP BY:
SELECT `group`, sum(sales)
FROM your_table
GROUP BY `group`
Edit to include back ticks for group. Without them you will receive an error
You should always avoid a SQL query in a loop unless there's no other solution. In this case, you can grab all the fields at once and have them in an array and add them up in PHP that way.

Get month-wise data from a table which has total year records

I have a table in that in one column I have a list of userid's separated by commas, and another column with date, this action is repeated for every day. How can I get month-wise data of who attends the class based on user id.
I need data like month-wise.
You need to separate userId else that will make very complicated sql and slow your server down. One record for date to userid. Then it is very simple;
select count(id) from `table` GROUP BY YEAR(record_date), MONTH(record_date)

group by mysql option

I am writing a converter to transfer data from old systems to new systems. I am using php+mysql.
I have one table that contains millions records with duplicate entries. I want to transfer that data in a new table and remove all entries. I am using following queries and pseudo code to perform this task
select *
from table1
insert into table2
ON DUPLICATE KEY UPDATE customer_information = concat('$firstName',',','$lastName')
It takes ages to process one table :(
I am pondering that is it possible to use group by and get all grouped record automatically?
Other than going through each record and checking duplicate etc.?
For example
select *
from table1
group by firstName, lastName
insert into table 2 only one record and add all users'
first last name into column ALL_NAMES with comma
EDIT
There are different records for each customers with different information. Each row is called duplicated if first and last name of user is same. In new table, we will just add one customer and their bought product in different columns (we have only 4 products).
I don't know what you are trying to do with customer_information, but if you just want to transfer the non-duplicated set of data from one table to another, this will work:
INSERT IGNORE INTO table2(field1, field2, ... fieldx)
SELECT DISTINCT field1, field2, ... fieldx
FROM table1;
DISTINCT will take care of rows that are exact duplicates. But if you have rows that are only partial duplicates (like the same last and first names but a different email) then IGNORE can help. If you put a unique index on table2(lastname,firstname) then IGNORE will make sure that only the first record with lastnameX, firstnameY from table1 is inserted. Of course, you might not like which record of a pair of partial duplicates is chosen.
ETA
Now that you've updated your question, it appears that you want to put the values of multiple rows into one field. This is, generally speaking, a bad idea because when you denormalize your data this way you make it much less accessible. Also, if you are grouping by (lastname, firstname), there will not be names in allnames. Because of this, my example uses allemails instead. In any event, if you really need to do this, here's how:
INSERT INTO table2(lastname, firstname, allemails)
SELECT lastname, firstname, GROUP_CONCAT(email) as allemails
FROM table1
GROUP BY lastname, firstname;
If they are really duplicate rows (every field is the the same) then you can use:
select DISTINCT * from table1
instead of :
select * from table1

Categories