Get highest value from results - mysql

I have a table
t1
--------------
id
date
val_1
val_2
I need to get 10 latest results and have them sorted from earlier to latest date, so I do it as
SELECT * FROM (
SELECT *
FROM myTable
WHERE project = $project_id
ORDER BY date DESC
LIMIT 10) AS results ORDER BY id ASC
Now, I need to get the highest value of val_1. I am trying to build a bar graph and would like to get the highest value because I need to divide it by the max height and use that result as a multiplier to stack-up val_1 and val_2 on top of each other without going outside of the graph's height.

So you want something like this?
SELECT *,
t2.biggest_value,
((t1.val_1/t2.biggest_value)*100) AS `%`
FROM myTable t1
JOIN (SELECT MAX(val_1) AS biggest_value,
project
FROM myTable
) AS t2
ON t2.project = t1.project
WHERE t1.project = $project_id
ORDER BY date DESC, id ASC
LIMIT 10
The JOIN gets the highest value on val_1 and the outer query is gathering all the data along with calculating the percentage of each val_1 based on the max value.
Live DEMO

Try like
SELECT val_1 as max_val FROM myTable ORDER by val_1 DESC LIMIT 1
You can also try with MAX like
SELECT MAX(val_1) as max_val FROM myTable

You may try this:
SELECT *, MAX(val_1) FROM (
SELECT *
FROM myTable
WHERE project = $project_id
ORDER BY date DESC
LIMIT 10) AS results ORDER by id ASC

Do something like;
SELECT MAX(val_1) FROM(SELECT *
FROM myTable
WHERE project = $project_id
ORDER BY date DESC
LIMIT 10) AS results ORDER by id ASC

See 3.6.1 The Maximum Value for a Column:
“What is the highest item number?”
SELECT MAX(article) AS article FROM shop;
You are free to use MAX() on query results as well:
SELECT MAX(val_1) FROM (SELECT …) t;

This query will give you the max with other columns : -
SELECT id,(select MAX(`price`) FROM `products` ) as FINAL from products
note :- This query assemble id and max price from the product table .i.e It associate max price with each record set.

Related

Show data where year and month but no value showing

I want show progress data where year = 2019 and month = 3 but I want to choose highest id to show so my code is like this
SELECT *
FROM projectmonthlyview2
where YEAR(tgl_masuk) =2020
And MONTH(tgl_masuk) =3
and id IN (select MAX(id)
FROM projectmonthlyview2
GROUP
BY project_id)
Order
by project_id asc
But not showing any value
Your question isn't exactly clear but maybe this?
SELECT * FROM `project_monthly`
where YEAR(tgl_masuk) =2020 And MONTH(tgl_masuk) =3
order by id desc
limit 1
I have solved it with the following query:
SELECT * FROM `projectmonthlyview2`
where id IN (select MAX(id) FROM projectmonthlyview2 Where YEAR(tgl_masuk) =2020 And MONTH(tgl_masuk) =3 GROUP BY project_id)
Order by project_id asc

GROUP BY and ORDER BY in UNION

I have this query:
SELECT category, description, price, date_added, datetime_created
FROM vc_expense
WHERE trip_id=? AND description LIKE ?
GROUP BY description, price
UNION SELECT category, description, NULL, NULL, NULL
FROM vc_expense_default
WHERE description LIKE ?
ORDER BY CASE
WHEN description LIKE ? AND price THEN 1
WHEN price THEN 2
ELSE 3
END, date_added DESC, datetime_created DESC
LIMIT 5
My problem is that when I GROUP the description+price on row #4, it doesn't take into account that I want the most recent results:
date_added DESC, datetime_created DESC
Is there a way to use ORDER BY after row #4 so I can get the newest items only, it doesn't seem to work because of the UNION
Thanks!
Edit:
The UNION was irrelevant, I just had put it inside parantheses, and get the latest items only from each group, like this:
SELECT e1.category, e1.description, e1.price, e1.date_added, e1.datetime_created
FROM vc_expense e1
LEFT JOIN vc_expense e2 ON (
e1.description=e2.description AND
e1.price=e2.price AND
e1.date_added < e2.date_added
)
WHERE e2.id IS NULL AND e1.trip_id = ? AND e1.description LIKE ?
From the docs:
https://dev.mysql.com/doc/refman/5.7/en/union.html
Use of ORDER BY for individual SELECT statements implies nothing about
the order in which the rows appear in the final result because UNION
by default produces an unordered set of rows
and here's what you need:
To apply ORDER BY or LIMIT to an individual SELECT, place the clause
inside the parentheses that enclose the SELECT:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

Retrieve the second latest record with same id

From the following four records, I want to select the OwnerId of second-latest record
ItemId OwnerId Date
11477 20981 2013-05-13
11477 1 2013-05-21
11477 21086 2013-05-22 #this is the one I'm talking about
11477 3868 2013-05-24
How to go about it?
This needs ItemID to be specified,
SELECT *
FROM TableName
WHERE ItemID = '11477'
ORDER BY DATE DESC
LIMIT 1,1
SQLFiddle Demo
However, if you don't want to specify the ItemID, and you want to get all second latest record for every ItemID, you can use a correlated subquery to generate a sequence number for every ItemID based on lastest DATE,
SELECT ItemId, OwnerID, Date
FROM
(
SELECT A.ItemId,
A.OwnerId,
A.Date,
(
SELECT COUNT(*)
FROM tableName c
WHERE c.ItemId = a.ItemId AND
c.Date >= a.Date) AS RowNumber
FROM TableName a
) x
WHERE RowNumber = 2
SQLFiddle Demo
select ownerid
from your_table
order by date desc
limit 1, 1
I think you can just to ORDER BY date descending, which will give you an order from newer to older, then LIMIT 1,1 to get only the second result, which should be the one you look for
SELECT *
FROM table
ORDER BY date DESC
LIMIT 1,1

mySQL query to return last record for each table

I have a mySQl db (name "stocks") with 50 tables, each tables with
id, symbol, date, time, open, high, low, close, volume as columns (9 columns).
I would like to know what is the last record for each table, ordered for date then time.
Should I have to ORDER BY all data for each table or there is a better way to just know last record?
I am asking help for a query that just return only last record for each table in db.
Thanks
PS For last record I mean most recent as Date then Time
There are two options how to do that:
-- I would use this only if you need more than one records
SELECT * FROM table ORDER BY date DESC LIMIT 1;
-- Way to go:
SELECT * FROM table WHERE date = (SELECT MAX(date) FROM table) LIMIT 1;
Don't forget to add index on date. If it's possible you add lot's of records at the same time you will have to add:
ORDER BY id DESC -- In case that date is highest for records for last records
ORDER BY time DESC -- Every other case
To the end of query
I am going to make the assumption that the record with the largest ID is the "last" (assuming strictly increasing sequential IDs that are unique within a table). If you have a better definition of "last" that could make a difference.
To get one "last" record, you could do:
Select * from table_1 where id = (select max(id) from table_1);
To get the results of all 50 tables into a single result set, you could do:
Select * from table_1 where id = (select max(id) from table_1)
union
Select * from table_2 where id = (select max(id) from table_2)
union
Select * from table_3 where id = (select max(id) from table_3)
union...
A MySQL-specific solution could be
Select * from table_1 order by id desc limit 1
union
Select * from table_2 order by id desc limit 1
union
Select * from table_3 order by id desc limit 1
union...
Based on your edit (where you actually define what you mean by "last"):
Select * from table_1 order by date desc, time desc, id desc limit 1
union
Select * from table_2 order by date desc, time desc, id desc limit 1
union
Select * from table_3 order by date desc, time desc, id desc limit 1
union...
Here is one way to do it without sorting the table:
select * from tab1
where time = (select max(time)
from tab1
where date = (select max(date) from tab1))
and date = (select max(date) from tab1)
It should be very fast, like, O(c), provided that both columns are indexed, otherwise the time will simply be O(n)

How can I select the row with the highest ID in MySQL?

How can I select the row with the highest ID in MySQL? This is my current code:
SELECT * FROM permlog WHERE max(id)
Errors come up, can someone help me?
SELECT * FROM permlog ORDER BY id DESC LIMIT 0, 1
if it's just the highest ID you want. and ID is unique/auto_increment:
SELECT MAX(ID) FROM tablename
For MySQL:
SELECT *
FROM permlog
ORDER BY id DESC
LIMIT 1
You want to sort the rows from highest to lowest id, hence the ORDER BY id DESC. Then you just want the first one so LIMIT 1:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement.
[...]
With one argument, the value specifies the number of rows to return from the beginning of the result set
SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;
This would return all rows with highest id, in case id column is not constrained to be unique.
SELECT MAX(id) FROM TABLENAME
This identifies the largest id and returns the value
Suppose you have mulitple record for same date or leave_type but different id and you want the maximum no of id for same date or leave_type as i also sucked with this issue,
so Yes you can do it with the following query:
select * from tabel_name where employee_no='123' and id=(
select max(id) from table_name where employee_no='123' and leave_type='5'
)
SELECT MAX(ID) FROM tablename LIMIT 1
Use this query to find the highest ID in the MySQL table.
Since both SELECT MAX(id) FROM table and SELECT id FROM table ORDER BY id DESC LIMIT 0,1 fulfill the goal, the interesting part is, which performs better.
SELECT MAX(id) FROM table: 152ms
SELECT id FROM table ORDER BY id DESC LIMIT 0,1: 25ms
(InnoDB-table with 55M rows on MySQL 8.0, 10 runs, average result)
Of course thats not representive, but gives an idea, that the ORDER BY method performs significantly better.
This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery
SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )
SELECT * FROM `permlog` as one
RIGHT JOIN (SELECT MAX(id) as max_id FROM `permlog`) as two
ON one.id = two.max_id