Using Delete, Update, Insert in MySQL - mysql

Good day!
First of all, I am new at MySQL, and I've got some problems with altering tables with query's.
Secondly, sorry for bad English, unfortunately, it's not my native language.
So yeah, I have some questions, and I will be very thankful if you will be able to help me.
I have 2 tables: Screenshot
Foreign key is 'manufact' from table Registred
So, I have few Query tasks I wanted to do, but can't figure out how to do them.
Here goes first task I did, I just want you guys to check, If I did it right.
Calculate fields from January and February where Car Manufacturer is VW.
SET Total = January + February WHERE Manufact = 3;
And here comes Query's I can't do:
Delete all information about car manufacturer, that had smallest amount of cars registred in January.
Here is what I came up with.
DELETE FROM Registered Order by January Limit 1;
But it didn't delete information from table 'manufacturer'.
What can I do there?
Here is hardest one so far:
Calculate all cars registered in January and February and save it in additional field. (Should be displayed as Int, without floating point.)
Code:
ALTER TABLE Registered Add Column alltotal Int;
UPDATE Registered
Set alltotal = Select SUM(February + January) From Registered;
What I wanted to do is, Create only 1 field, where Sum of all February and January fields will be calculated.
Any suggestions so far?
P.S If I will be able to do these, I will be able to complete other tasks myself :)
P.S.2 I am new here, so please sorry for bad Question editing. I am doing as in tutorial I found but it's hellish for me. I tried my best :)

Let's break this down problem by problem. The first one is:
Delete all information about car manufacturer, that had smallest amount of cars registered in January.
The first thing we need to do is write a subquery that determines which manufacturer that is. We can do so by selecting the id of the row in registracija with the minimum value for January. We can do that using ORDER BY, which you caught on to:
SELECT vieglas
FROM registracija
ORDER BY january
LIMIT 1;
Now that we have that id, we can delete from that table using the WHERE clause:
DELETE FROM registracija
WHERE vieglas = (SELECT vieglas FROM (SELECT * FROM registracija) t ORDER BY january LIMIT 1);
For information on why I included the SELECT * FROM registracija, see this answer.
To see an SQL Fiddle of that in action, check this: http://sqlfiddle.com/#!9/c81d5/1
For the second part:
Calculate all cars registred in January and February and save it in additional field. (Should be displayed as Int, without floating point.)
We can use the addition operator along with an update command to put this total inside the Total column like this:
UPDATE registracija
SET total = (january + february);
For the SQL Fiddle of the update, see this: http://sqlfiddle.com/#!9/f5b28/1

for deleting all record which has had smallest amount of cars registred in January delete from 'Registracija' where 'January' =select min('January') from Registracija

Try following:
1) Total Count For January & February
SELECT (January+February) AS TOTAL from Registrant where Vieglas = 3
2) Delete Query
DELETE FROM Registrant INNER JOIN Vieglas Order By Registrant.January Limit 1

Related

MS Access: Calculate difference when two criteria meet

I have an MS Access related question. I have a table that looks like this:
Table1
What I need to do is this:
1. Find deadline 29.01.2017 (first month of the year),
2. look at the corresponding AccountNumber and SubAccountNumber,
3. find deadline 28.02.2017 (so the next month) that matches with the AccountNumber and SubAccountNumber of the previous month,
4. subtract the Amounts,
5. and display the result.
In this example (Table 1): The first deadline of 29.01.2017 has the AccountNumber 1 and SubAccountNumber 23 as well as the Amount 400€. Looking for the next month that matches AccountNumber and SubAccountNumber, we find the value 300€. I would now have to subtract 300€ from 400€ and put this in the field that I have added (see also Table 2).
What I have done so far is concatenate the two attributes AccountNumber and SubAccountNumber, so my table now looks like this:
Table2
I thought it would be easier this way, because now I can look for the first month/deadline (29.01.2017), get the corresponding CONCAT, look for the next month/deadline that has the same CONCAT, and subtract the amounts.
Seeing as I am new to Access though, I am clueless as to how to go about this. Any hint would be greatly appreciated. If you think that my approach using a concatenation is not target-aimed or if I haven't made the problem clear enough, let me know.
PS I read online that Access offers an if-else statement - would that be an idea?
That should get you there or very close:
SELECT T1.ACCOUNTNUMBER, T1.SUBACCOUNTNUMBER, T1.AMOUNT-T2.AMOUNT AS AMOUNTDIFF
FROM Table1 T1
INNER JOIN Table1 T2
ON T1.ACCOUNTNUMBER=T2.ACCOUNTNUMBER
AND T1.SUBACCOUNTNUMBER=T2.SUBACCOUNTNUMBER
AND DateDiff('m',DateAdd('d',1,T1.DEADLINE), DateAdd('d',1,T2.DEADLINE))=1
WHERE T1.DEADLINE=#29.01.2017#
Make sure whatever date format you use with WHERE is a valid date format for your locale. Obviously substitute Table1 with the actual name of your table.
I do not have an easy way of testing this so there may be typos.

NOT IN use in same table

im kinda new to the site, as a user atleast, been finding my answers in here for a long time :)
My problem is this, i work at a rather big hospital, where we run a mysql db containing all our employees, and now i need to make a query that can show my all employees who's employment ended during 2017. The thing is, since its a big hospital where ALOT of departments alot of the employees change jobs internally between the different departments, and everytime they do a new row in the table is created with their new employment details.
in every row for every employment, it contains their employer ID, the start date and end date, and some other info. the end date, can be either a date ofc, it can be NULL or 0000-00-00, the last 2 indicates that their imployment has no end date.
So its easy enough to do a simple search containing all users with and end date containing 2017
(SELECT * FROM table WHERE enddate LIKE '%2017%')
and it gives me all the users who has an end date in 2017, problem is ofc, that it does not account for users who might just have switched department, and has ended its employment in one department to start in another.
So what im trying to do is get all users with a 2017 enddate and then all people that has no enddate or and enddate after 2017 and then remove them from the list of people with an 2017 enddate.
i tried the following:
SELECT *
FROM users
WHERE enddate LIKE '%2017%' AND employid NOT IN
(
SELECT * FROM users WHERE enddate LIKE '%0000%'
);
i know it doesnt really over all i wanted, but at first i was really just trying to get the NOT IN to work in some way, and then after that work my way on to include the rest, but i cant even get that to work.
I tried searching for some uses of NOT IN, but it seemed to always be some very simple uses of them and always on 2 different tables.
I hope i explained it correct, as stated im still kinda new to mysql and sql in general :)
To solve the NOT IN Problem you can use this query:
SELECT * FROM users
WHERE enddate LIKE '%2017%' AND employid NOT IN
( SELECT employid FROM users WHERE ansslut LIKE '%0000%' );
Note that inside the NOT IN Select you must specify the "employid" field.
See if this work for you
You are matching for a column and the you shoul return a comparable value from the subselect related to NOT IN
eg asssuming you emp_id match with user id from you r subselect you should
SELECT *
FROM users
WHERE enddate LIKE '%2017%'
AND employid NOT IN (
SELECT user_id FROM users WHERE ansslut LIKE '%0000%'
);

Access - Only take row from table of max year

I have a table in Access that holds students previous qualifications. It has multiple lines per students dependent on the number of previous qualifications they have. The data has the year of the qualification in it.
I want to create a sub-query that only has the most recent qualification in it (i.e. the latest year). I have tried max and last in the query for the year, but because I am bringing out other fields, it is still pulling out all the qualifications rather than just the latest one.
StudentID Qualificationlevel QualificationType MaxOfYearAwarded
10203 Postgraduate/Masters MSc 2016
10203 Undergraduate BSc 2013
So in the example above, I want to ONLY have the top row being pulled as it is 2016 and therefore later than 2013.
Any help would be appreciated.
Quite a simple task
Just use a subquery as a condition.
To group the query, use a WHERE condition in the subquery. Note that, since we're querying the same table twice, we will need to use table aliases
SELECT *
FROM MyTable t
WHERE t.YearAwarded = (
SELECT Max(s.YearAwarded)
FROM MyTable s
WHERE s.StudentID = t.StudentID
)

Getting rows in Microsoft Access to refer to other rows

I have a Microsoft Access table of data with 3 fields: "part_number", "date_of_price_change" and "new_price", but I need to convert the "new_price" field to show the "price_change", rather than the full "new_price" of each part on each date.
This will obviously involve some process that looks at each unique part number on each date and looks up the price of the record with the same part number with the next earliest date and deduct the prices to get the price change.
Problem is, I have no idea how to do this in Access and there are too many records for Excel. Can anyone assist with how to do this in Access? (Note that date changes can happen any time and are not periodic).
Many thanks in advance.
Ana
Add the new column price_change as a Money data type, then run a query something like below. Make sure you backup the table first with an APPEND table to a new table, just in case. Since it is a new column i may not matter.
UPDATE
T1
SET
T1.price_change = T1.new_price - Nz((SELECT top 1 T2.new_price from MyTable T2 WHERE T2.part_number = T1.Part_Number ORDER BY date_of_price_change DESC),0)
FROM
MyTable T1

Showing all duplicates, side by side, in MySQL

I have a table like so:
Table eventlog
user | user_group | event_date | event_dur.
---- ---------- --------- ----------
xyz 1 2009-1-1 3.5
xyz 2 2009-1-1 4.5
abc 2 2009-1-2 5
abc 1 2009-1-2 5
Notice that in the above sample data, the only thing reliable is the date and the user. Through an over site that is 90% mine to blame, I have managed to allow users to duplicate their daily entries. In some instances the duplicates were intended to be updates to their duration, in others it was their attempt to change the user_group they were working with that day, and in other cases both.
Fortunately, I have a fairly strong idea (since this is an update to an older system) of which records are correct. (Basically, this all happened as an attempt to seamlessly merge the old DB with the new DB).
Unfortunately, I have to more or less do this by hand, or risk losing data that only exists on one side and not the other....
Long story short, I'm trying to figure out the right MySQL query to return all records that have more than one entry for a user on any given date. I have been struggling with GROUP BY and HAVING, but the best I can get is a list of one of the two duplicates, per duplicate, which would be great if I knew for sure it was the wrong one.
Here is the closest I've come:
SELECT *
FROM eventlog
GROUP BY event_date, user
HAVING COUNT(user) > 1
ORDER BY event_date, user
Any help with this would be extremely useful. If need be, I have the list of users/date for each set of duplicates, so I can go by hand and remove all 400 of them, but I'd much rather see them all at once.
Thanks!
Would this work?
SELECT event_date, user
FROM eventlog
GROUP BY event_date, user
HAVING COUNT(*) > 1
ORDER BY event_date, user
What's throwing me off is the COUNT(user) clause you have.
You can list all the field values of the duplicates with GROUP_CONCAT function, but you still get one row for each set.
I think this would work (untested)
SELECT *
FROM eventlog e1
WHERE 1 <
(
SELECT COUNT(*)
FROM eventlog e2
WHERE e1.event_date = e2.event_date
AND e1.user = e2.user
)
-- AND [maybe an additionnal constraint to find the bad duplicate]
ORDER BY event_date, user;
;