SQL, 2 tables sum of a field - php

I have 2 tables, student and family.
Half of the students come Sundays, the other half Saturdays
Some families have more than one child.
Families pay fees for the school. Some families because of some critearia have a discount.
"discount" is a field in 'family' table
In a report I need to calculate the sum of all the discounts of all families that take advantage of a discount (by day).
When I do so, if a family has 2 children, the result returns double of the discount, if 3 children 3 x discount....
My Query:
$select_total_discounts =
"SELECT SUM(Discount) AS total_discounts
FROM family, student
WHERE family.Family_ID=student.Family_ID
AND student.Day like '%$Day%' ;" ;
$query= mysql_query($select_total_discounts,$conn) ;
$row = mysql_fetch_assoc($query);
$total_discounts= $row['total_discounts'];
Thank you in advance

If I understood your question correctly, you want to calculate the discounts by family disregarding the amount of students it has. So it'd be like this (change the day value by your variable):
SELECT SUM(Discount) AS total_discounts
FROM family
WHERE family.Family_ID in (select student.Family_ID from student where student.Day like 'Monday')
So it sums the discounts of the families that have at least one student from the specified day. If it has one, two, three or more students, it will not affect the result.
Working SQLFiddle: http://sqlfiddle.com/#!2/9b9793/1

It is not really full answer, but I posted it here, so it would be readable.
I think you are looking for something like UNION:
SELECT sum(value) FROM ((SELECT value FROM table) UNION ALL (SELECT value FROM table2)) sq
UNION merges your tables vertically.

Related

Subtract two fields in two different tables to insert different into a third field in second table

We have a db that was converted by a third party from cube cart to prestashop. Mostly things went fine but recently found a couple thousand products that lack a discount reduction value.
I have found bits and pieces on how to do what we need but I just need help. This is my first foray into sql/php so bear with me and dont laugh too much.
Get a product id # from the product_id column in Table1
Get the base price amount from price column in Table1
Find every instance of the product id listed in Table2 (can be up to 3 tiers of discount for each product)and do the next steps
Get the discount price from the discount column in Table2 for each instance of that product.
Subtract price (table1) from discount (table2) to find the reduction amount.
Insert reduction amount into the reduction column in Table2.
Repeat this for every row in Table2
After research I learned enough to do it within the same table but this playing with values from two different tables my brain goes "Im outta here."
SELECT *, (price - discount) AS Sum FROM Table1
I found some examples but nothing crosses over close enough to my needs to work or my syntax is messing things up.
Even a nudge in the right direction would mean a lot.
select b.*, (b.price - a.discount) as sum
from table2 b
left join table1 a on b.product_id = a.product_id
So if I understand this correctly table1 has product Id, base price, and table2 has discount?
It looks like you want to take table 2 and just add a column that has price after discount on every row?
Let me know and I can try and guide you further....

Managing multiple SQL statements in loop

I have 3 sql statements that I need to print to a html table.
1: selects all employee initials that has made an order between two dates.
2: sums up the count of each employee's orders between two dates.
3: sums up each employee's total amount of money spent between two dates.
All data is in a table: Orders(orderNr, itemNr, orderAmount, employee, date, price)
Now, I have to print all three into a table, and I am struggling to figure out how to loop through them correctly while having all the right resultsets.
The table should show: Employee - Amount of orders - Total price
Any help is greatly appreciated.
Try this
SELECT employee, COUNT(DISTINCT(orderNr)) AS orders_count, SUM(price) AS total_price FROM Orders WHERE
date BETWEEN '$startdate' AND '$enddate' GROUP BY employee

How to Query and Arrange Two Similar Tables

I have one student table links to two scores tables which are exactly the same structures. The only different is that one table will stores high scores, the other table stores low scores. Now I need to query both high and low score tables, it will list all subjects scores with student name if it is from high score table and scores with name is student if its from low score table, and I need to order the result by time.
SELECT u.student_name,
a.subject1_score,
a.subject2_score,
a.subject3_score,
a.subject4_score,
a.subject5_score,
a.exam_date
FROM Student u
INNER JOIN High_Score_Table a
On u.student_id = a.student_id
ORDER BY a.exame_date = time
Then for low_score_Table I will have almost same query except that the student name will equal to Student by default.
Then I will need to put this together in a list and order by time. How could I do that shorter and better ?
Btw, I can merge two tables low and high_score into one, and add a column called "flag" into that, whenever the flag value equal to "show" then I show student name with all score records, else "hidden" I will just show "Student" and all score records. How could I do that in one query ?
It sounds like you need a UNION, because you are concatenating two distinct result sets - one from High_Score_Table and one from (presumably) Low_Score_Table:
select s.student_name,
h.subject1_score,
h.subject2_score,
h.subject3_score,
h.subject4_score,
h.subject5_score,
h.exam_date
from High_Score_Table h
join Student s on h.student_id = u.student_id
union all
select 'student' as student_name,
l.subject1_score,
l.subject2_score,
l.subject3_score,
l.subject4_score,
l.subject5_score,
l.exam_date
from Low_Score_Table l
order by exam_date
The takeaway here is an ORDER BY clause in a union sorts over the entire result set - which is in this case exactly what you want.

PHP/MySQL - Count number of sales made and display that number and who sold them

I'm working on a PHP application for University which pretends I buy and resell a specific item to/from countries.
I have a table which contains transaction IDs and the names of the countries that made them.
I've been trying to count up the number of times a specific country's name appears in the database table then print out a table on the webpage showing each countries name and the number of times they appear in the table like below, but I can't find any examples of this kind of thing anywhere, they're always too different to be of much help. I would also like to order the table by max to min count and also be able to limit the number of countries shown using radio buttons (which I've already got working).
countryName | numberOfSales
Belize | 10
Brazil | 6
Cameroon | 64
Colombia | 23
Costa Rica | 47
You need to select the country and count, then group by the country. If you want to order it you need to add that on as well.
SELECT
countryName,
count(*) as numberOfSales
FROM
sales
GROUP BY
countryName
ORDER BY
numberOfSales DESC
This query will have 2 columns in the results. The country names and the number of times they appear according to the grouping. We are grouping all of the records by the country name column. In the query, we name the column numberOfSales, so we can use that when ordering it so that the countries will be in order from max to min in numberOfSales.
If you have two tables in your database (MySql in my case), one where you store the different countries and one for the sales/orders.
Table countries:
id INT
country VARHCAR(255)
Table: sales:
id INT
country_id INT
title VARCHAR(255)
Here there is a 1:many relationship between the two tables. One country can have many sales, but a sale can only belong to one country.
You can then fetch the number of sales for specific country by running the following SQL query.
If you want to find the number of sales for Denmark you could do:
SELECT countries.country, COUNT(*) AS numberOfSales
FROM countries
JOIN sales
ON sales.country_id = countries.id
WHERE countries.country = 'denmark';
If you want to see the total number of sales for each country you can use the following SQL query:
SELECT countries.country, COUNT(*) AS numberOfSales
FROM countries
JOIN sales
ON sales.country_id = countries.id
GROUP BY countries.country;
Here the GROUP BY clause will fetch the result for each of the countries in your countries table. You can add LIMIT clause if necessary.
I hope this doesn't complicate things too much. You will thank me later by using two tables (I do not know if you already do. If you do, NICE).
Related to counting identical rows in MySql: Count number of identical rows in MySQL with PHP
Best regards.

limit the number of a field value in search results

I run real state website, which allows different users to add their properties.
When someone searches for a specific criteria, we use a select statement along with the specified conditions to select the matched properties, do the paging bit and display the results.
We use a rating algorithm to rate each property and use it to priorities the displayed properties.
A simplified version:
name type bedrooms user score
green house sale two bedrooms alex 6
Blue one rent three bedrooms jack 6
Blue one sale three bedrooms jack 4
gray one sale three bedrooms jack 6
green one rent three bedrooms jack 6
purple one rent three bedrooms jack 6
green one rent three bedrooms jack 6
green one rent three bedrooms gary 6
Now the problem is that sometimes a few properties have the same score. In these cases I don't want properties from one user to dominate a search result page, I want to set a limit to display a maximum of three properties of any given user in a search result page.
In the example, I don't want the properties owned by jack to dominate the first page, and properties of other users go to second page. This would upset other users and create a bad experience for visitors.
If I wanted to show only one property for a given user, I'd use Group by, but I'm not sure what to limit to a larger number ( three for instance). Is there anything I could do in mysql to achieve this?
EDIT:
Sorry if it wasnt clear enough.
The use field displays the user who added the particular property. A sample query could be
SELECT * FROM properties WHERE type = 'sale' LIMIT 5 ORDER BY score
The result could be five properties, all added by jack. I want to make sure that no more than thee properties added by a particular user, are included in the results. This way properties added by other users would have a chance to be displayed.
Use DISTINCT it will solve your problem.In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values.The DISTINCT keyword can be used to return only distinct (different) values. Example
SELECT DISTINCT user FROM table_name;
use DISTINCT in your query something like this example
SELECT DISTINCT column_name,column_name from table;
try with this and change string your_table with your table name
SELECT
*
FROM
`your_table`
LEFT JOIN
(SELECT * FROM `your_table` LIMIT 3) as lr on lr.user = `your_table`.user
GROUP BY
user
reference link
UPDATE 2
if you want to order by your score you can use
SELECT
*
FROM
`your_table`
LEFT JOIN
(SELECT * FROM `your_table` ORDER BY score DESC LIMIT 3) as lr on lr.user = `your_table`.user
GROUP BY
user

Categories