SQL max with additional column - mysql

I want to select a latest record from MySQL table using MAX. Date column that I apply MAX to is selected properly, but second column the ID is not. Following screenshot expalins this best:
As you see 1_2018 is selected instead of 15_2018.

You could use your query as a sub query to pick the row(s) for max created value
select *
from business_trip
where created = (
select max(created )
from business_trip
where year_id LIKE '%_2018'
)

SELECT created, year_id
FROM business_trip
WHERE created = (SELECT MAX(created) FROM business_trip);
In this case I'm here using sub query to satisfy your requirement. Other answers used ORDER BY (which will not give the expected answer until the year_id is MAX) and other with MAX() in SELECT will not pull the related record with latest created value.
In my query I'm also avoided use of check over year_id so this will always return you the record with latest created value.

you can sort by the created and then LIMIT 1 to get only a single record. Something like this
SELECT created,year_id
FROM business_trip
WHERE year_id LIKE '%_2018'
ORDER BY created DESC LIMIT 1;

Related

How to select Point In Time record

I have a MariaDB 10.2.21.
My table contains records that include a 'ChangeDate' field like this: '2019-09-18 10:57:26'.
I want to do a SELECT based on a timestamp, and get the nearest previous record to return.
This allows me to do a 'point-in-time' selection providing me with field values as they were at that moment.
I seeked StackOverflow but do no recognize a proper solution.
Any hints? Thanks!
Try following Query
SELECT *
FROM my_table
WHERE ChangeDate < '2019-09-18 10:57:26'
ORDER
BY ChangeDate DESC
LIMIT 1

Mysql DISTINCT with more than one column (remove duplicates)

My database is called: (training_session)
I try to print out some information from my data, but I do not want to have any duplicates. I do get it somehow, may someone tell me what I do wrong?
SELECT DISTINCT athlete_id AND duration FROM training_session
SELECT DISTINCT athlete_id, duration FROM training_session
It works perfectly if i use only one column, but when I add another. it does not work.
I think you misunderstood the use of DISTINCT.
There is big difference between using DISTINCT and GROUP BY.
Both have some sort of goal, but they have different purpose.
You use DISTINCT if you want to show a series of columns and never repeat. That means you dont care about calculations or group function aggregates. DISTINCT will show different RESULTS if you keep adding more columns in your SELECT (if the table has many columns)
You use GROUP BY if you want to show "distinctively" on a certain selected columns and you use group function to calculate the data related to it. Therefore you use GROUP BY if you want to use group functions.
Please check group functions you can use in this link.
https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html
EDIT 1:
It seems like you are trying to get the "latest" of a certain athlete, I'll assume the current scenario if there is no ID.
Here is my alternate solution:
SELECT a.athlete_id ,
( SELECT b.duration
FROM training_session as b
WHERE b.athlete_id = a.athlete_id -- connect
ORDER BY [latest column to sort] DESC
LIMIT 1
) last_duration
FROM training_session as a
GROUP BY a.athlete_id
ORDER BY a.athlete_id
This syntax is called IN-SELECT subquery. With the help of LIMIT 1, it shows the topmost record. In-select subquery must have 1 record to return or else it shows error.
MySQL's DISTINCT clause is used to filter out duplicate recordsets.
If your query was SELECT DISTINCT athlete_id FROM training_session then your output would be:
athlete_id
----------
1
2
3
4
5
6
As soon as you add another column to your query (in your example, the column called duration) then each record resulting from your query are unique, hence the results you're getting. In other words the query is working correctly.

MYSQL: Select a row for a given filter and the maximum value of key

I have a table (tUsuariosLog) which contains the history of updated information for a given user. So If I want to read the current information of a given user then I need to row with the greatest key value in key column (the key column has auto_increment).
Here is the query that I use to get it.
SELECT * FROM tUsuariosLog WHERE cUid = '15' AND cKeyid = (SELECT MAX(cKeyid) FROM tUsuariosLog WHERE cUid = '15')
It seems that this is an overcomplicated way of achieving what I want (it does work though).
My question is if there is a better way to get what I want that a query within a query.
How about using order by and limit?
SELECT ul.*
FROM tUsuariosLog ul
WHERE cUid = 15
ORDER BY cKeyid DESC
LIMIT 1;
I am guessing that cUid is a number, not a string, so I removed the single quotes.
For performance, you want an index on tUsuariosLog(cUid, cKeyid).

MySQL query - Use SELECT inside an UPDATE

I'm trying to select a particular row in a database using SELECT and OFFSET. The result I get is logical and I do get the desired row I want. But then I need to UPDATE that same specific row so I do something like that:
UPDATE table
SET value=1
WHERE value IN (SELECT * FROM(
SELECT value FROM table WHERE some criteria LIMIT 1 OFFSET 2) temp_tab);
Now what I expect from this code is to UPDATE the selected row ONLY. Instead it Updates ALL rows in the datatable and sets their value to 1.
When I use only:
SELECT * FROM(
SELECT value FROM table WHERE some criteria LIMIT 1 OFFSET 2) temp_tab
I get only 1 row as the output. (LIMIT 1 OFFSET 2 makes sure I do get the 1 row and it's the 2nd available) I am not exactly sure what I am doing wrong or how I am supposed to achieve this.
Note: I do have to use SELECT and not some other method using unique ID of the row or something similar.
Any help would be greatly appreciated.
First, when using LIMIT and OFFSET you need to use ORDER BY as well. Otherwise the row you get is indeterminate.
One method uses LIMIT within the UPDATE itself. However, UPDATE doesn't allow OFFSET. So:
UPDATE table
SET value = 1
WHERE some criteria
ORDER BY ??
LIMIT 1;
The best method would use a unique id. You can do this with the double subquery approach:
UPDATE table
SET value = 1
WHERE id IN (SELECT id
FROM (SELECT id
FROM table
WHERE some criteria
ORDER BY ??
LIMIT 1 OFFSET 2
) t
);
If you don't have a single unique id, you can use multiple columns that uniquely define a single row.

How do I return a single record using max function and aggregation on table with different values

I have a single table that looks like this:
I need to return the row with the most recent LastVisit Date as highlighted above from a single table.
I tried using the MAX function on the date but the problem is, I cannot aggregate the other columns because the values are not the same, this returns all three rows.
How do I get only the latest row highlighted?
You can use DMax to get the most recent LastVist date.
DMax("LastVisit", "YourTable")
Then to get the row (or rows) with the same date, use that DMax expression in a query WHERE criterion.
SELECT *
FROM YourTable
WHERE LastVisit = DMax("LastVisit", "YourTable");
Another way to do it would be to use a subquery instead of DMax to get the latest date.
SELECT *
FROM YourTable
WHERE LastVisit = (SELECT Max(LastVisit) FROM YourTable);