Can't Sum a New Data In MySQL After Inner Join - mysql

Got some problem after using inner join, this is my query
> insert into total(ID,Grade) select midsemester.ID,(midsemester.grade +
> endsemester.grade) as total from midsemester inner join endsemester on
> midsemester.ID = endsemester.ID
This is the table:
Table name: midsemester
ID Grade
1 10
2 30
3 40
Table name: endsemester
ID Grade
1 30
2 40
3 20
and i need to sum these table to new table called total. This is the results that i was hoping.
Table name: total
ID Grade
1 40
2 70
3 60
I actually just need to sums up the grade's value using the id for the 3rd table. And tried several times using inner join, it's working. But when I try to insert a new data, the table of total can't sum a new data. Would appreciate any help, thanks! :)

I think you wang union all with an aggregation:
insert into total(ID,Grade)
select ID, sum(grade) as total
from (select id, grade from midsemester union all
select id grade from endsemester
) me
group by id;
However, this is a bad structure for the grades. You should store them all in one table, with a column indicating whether the grade is "midsemester" or "endsemester".

Related

How to count multiple occurrences of a user ID across multiple columns within a single table

I have two tables, a users table and an orders table.
Users table has ID, firstName, LastName, etc.
Orders table has OrderID, AssignedToUserID, UserIDWhoCheckedOrder, UserIDWhoPackedOrder, UserIDofWhoCreatedInvoice
Currently I have this query that generates a count of a orders assigned to each user in the orders table.
SELECT
COUNT(T1.orderID) AS TOTAL,
T2.usersFirstName
FROM
Global_Orders T1
LEFT JOIN Global_Users T2 ON
T1.AssignedToUserID = T2.usersGlobalID
WHERE T1.AssignedToUserID IS NOT NULL
GROUP BY
T1.AssignedToUserID
RESULT
User First Name
Total Assigned
John
15
Jane
20
What I am needing to accomplish is to add more count columns to the above table. This data is also found in other columns such as UserIDWhoCheckedOrder, UserIDWhoPackedOrder, and UserIDofWhoCreatedInvoice. For the below result.
User First Name
Total Assigned
Total Checked
Total Packed
Total Invoiced
John
15
5
12
33
Jane
20
0
6
0
I am really lost how to group counts for the other columns within the same query. I am generating the first table with PHP if that info is useful. Thank you so much in advance for any guidance.

Select redundant rows only, not the original

So I'm tasked with cleaning up a system that has generated redundant orders.
Data example of the problem
ORDER ID, SERIAL, ...
1 1
2 1
3 2
4 2
5 3
6 3
7 3
The above data shows that 2 orders were generated with serial 1, 2 orders with serial 2, and 3 orders with serial 3. This is not allowed, and there should be only one order per serial.
So I need a query that can identify the REDUNDANT orders ONLY. I'd like the query to exclude the original order.
So the output from the above data should be:
REDUNDANT ORDER IDS
2
4
6
7
I can easily identify which orders have duplicates using GROUP BY and HAVING COUNT(*) > 1 but the tricky part comes with removing the original.
Is it even possible?
Any help is greatly appreciated.
As posted in the comments, here's one way to achieve this:
SELECT T1.ORDER_ID as redundant
FROM thetable T1
LEFT JOIN
(
SELECT SERIAL, MIN(ORDER_ID) AS firstorder
FROM thetable
GROUP BY SERIAL
HAVING COUNT(*) > 1
) T2 ON T1.ORDER_ID=T2.firstorder
WHERE T2.firstorder IS NULL
SQL Fiddle

Guidance required for sql query

I have a database with one table as shown below. Here I'm trying to write a query to display the names of medication manufactured by the company that manufactures the most number of medications.
By looking at the table we could say the medication names which belongs to the company id 1 and 2 - because those company manufactures the most medication according to this table, but I'm not sure how to write a query for selecting the same i said before.
ID | COMPANY_ID | MEDICATION_NAME
1 1 ASPIRIN
2 1 GLUCERNA
3 2 SIBUTRAMINE
4 1 IBUPROFEN
5 2 VENOFER
6 2 AVONEN
7 4 ACETAMINOPHEN
8 3 ACETAMINO
9 3 GLIPIZIDE
Please share your suggestions. Thanks!
Several ways to do this. Here's one which first uses a subquery to get the maximum count, then another subquery to get the companies with that count, and finally the outer query to return the results:
select *
from yourtable
where companyid in (
select companyid
from yourtable
group by companyid
having count(1) = (
select count(1) cnt
from yourtable
group by companyid
order by 1 desc
limit 1
)
)
SQL Fiddle Demo
This Query might work. I have not tested but the logic is correct
SELECT MEDICATION_NAME
FROM TABLE where
COMPANY_ID=(SELECT
MAX(counted)
FROM ( SELECT COUNT(*) AS counted FROM TABLE ) AS counts);

How to add different columns from different tables?

I just wanted to add different columns from different tables... Has anyone any idea on how to do that?
Consider I have 3 tables as below
tv sales
AC sales
cooler sales
And the tables data as follows
1)Tv Sales
Id Date NoOfSales Totalamount
1 03/05/2014 10 10000
2 04/05/2014 20 20000
3 05/05/2014 30 30000
2)Ac Sales
Id Date NoOfSales Totalamount
1 03/05/2014 10 50000
2 04/05/2014 20 60000
3 05/05/2014 30 70000
3)cooler Sales
Id Date NoOfSales Totalamount
1 03/05/2014 10 30000
2 04/05/2014 20 60000
3 05/05/2014 30 70000
Now I want to add the "Totalamount" from all the tables for a particular "date"
for example I need totalamount on 03/05/2014 as 90000
In MySQL, the easiest way to do this is with union all and aggregation:
select date, sum(totalamount) as TotalSales
from ((select date, totalamount from TvSales
) union all
(select date, totalamount from AcSales
) union all
(select date, totalamount from CoolerSales
)
) t
group by date;
The reason you want to use union all is in case the dates are different in the various tables. A join makes it possible to lose rows.
Second, having three tables with the same format is an indication of poor database design. You should really have one table with the sales and a column indicating which type of product it refers to.
You could solve your problem by making a union of the information you want to aggregate on the different tables and them sum the amounts. This would look like:
SELECT t.Date,SUM(t.Totalamount)
FROM
(
SELECT Date,Totalamount
FROM tvSales
UNION ALL
SELECT Date,Totalamount
FROM acSales
UNION ALL
SELECT Date,Totalamount
FROM coolerSales
) t
WHERE t.Date='03/05/2014'
GROUP BY t.Date
It is important that the fields of the union have the same name and type. In case they haven't the same name you should create common aliases for the 2 columns across the 3 select queries and then work with these aliases on the main query. Also the UNION should be performed including the ALL keyword in order to avoid eliminating duplicate records across the three tables.

Mysql Query problem?

ID NAME AMT
1 Name1 1000
2 Name2 500
3 Name3 3000
4 Name1 5000
5 Name2 2000
6 Name1 3000
consider above table as sample.
am having a problem in my sql query, Am using like this.
Select name,amt from sample where amt between 1000 and 5000
it returns all the values in the table between 1000 and 5000, instead I want to get maximum amount record for each name
i.e.,
3 name3 3000
4 name1 5000
5 name2 2000
select name, max(amt) from sample group by name
You'll have problems getting the id, though, as there may be more than one.
you should group by NAME:
SELECT `name`,MAX(amt) from sample GROUP BY `name` where amt between 1000 and 5000
If you only need ONE of the ids that contains the MAX(amt), then this will do the trick:
SELECT id, name, MAX(amt)
FROM sample
WHERE amt BETWEEN 1000 AND 5000
GROUP BY name;
If you need all the ids, then it gets more complicated. Two queries are required, plus a temporary table:
CREATE TEMPORARY TABLE maxamts
SELECT name AS maxname, MAX(amt) AS maxamt
FROM sample
WHERE amt BETWEEN 1000 AND 5000
GROUP BY maxname;
SELECT GROUP_CONCAT(id), maxname AS name, maxamt AS amt
FROM maxamts
LEFT JOIN sample ON ((maxname = sample.name) AND (maxamt = amt))
GROUP BY maxname;
In short: Create a temporary table from the query that finds each name/max(amt) pair, then use that temporary table to join back on the original table and pull out the IDs matching the name/amount combinations.
Just remember that group_concat is by default limited to 1,024 characters, (show variables like '%group_concat%' to see the max length on your server), so if you've got a large dataset, increase that limit, or remove the group_concat and group by from the second query and parse the information in your application.
select id, name, amt from sample where amt = (select max(amt) from sample)
that should return all records that have the max amt from the sample table
edit:
select id, name, amt
from sample
where amt = (
select max(amt)
from sample
where amt between 1000 and 5000)
this query will return all records that have an amount equal to the max amount between 1000 and 5000