I want to redistribute some values in a table in a database I manage.
Firstname(varchar), Lastname(varchar), Date(date), Icecream_consumed(int)
Where the combination of Firstname, Lastname, and Date make the primary key for this table. Changing the structure of this table is not an option.
There are 80 total unique combinations of Firstname and LastName in the database but i want to get that number down to 5 and add some of the records with the smaller total Icecream_consumed to the ones with the highest total. So that only the top 5 FirstName and LastName combinations have all the Icecream_consumed count.
For example if I execute the query:
SELECT Firstname, Lastname, SUM(Icecream_consumed)
FROM table_name
GROUP BY Firstname, Lastname
ORDER BY SUM(Icecream_consumed);
I want it to only have 5 results, not 80. How can I modify the records within the table to reflect this without manually updating each record? A simple update would not work as it would be inserting where existing records with the same primary key exist.
EDIT: I noticed that the column ID was kind of ambiguous. So I removed it from this example.
EDIT2: Here is an example:
Existing:
Firstname, Lastname, SUM(Icecream_consumed)
John Doe 1500
Joe Doe 1400
Alex Foo 1111
John Foo 1000
Ben Foo 999
Sue Cool 500
Bill Smith 200
Ben Smith 150
I want to change the tables so that the sum(icecream_consumed) values associated with sue, cool, bill smith, and ben smith are associated with john doe so that only 5 results are visible. However if i tried to update all records for sue cool to be john doe instead, there would be a conflict with the primary keys since they both might have values for icecream_consumed for the same dates.
The outcome might look like:
John Doe 2000
Joe Doe 1600
Alex Foo 1261
John Foo 1000
Ben Foo 999
Working example on SQL Fiddle: http://sqlfiddle.com/#!2/0e8ab/1
Because MySql cannot run sub selects in update statements if the subselect is the same table as the one in the update, you need to first temporarily copy the data into another table – so DO NOT run this when data is still going into the database as it is not an atomic operation. You need to shut down any applications using the database first.