I have the scenario:
A table with POSITION and a value associated for each position, BUT I have always 4 values for the same position, so an example of my table is:
position | x| values
1 | x1 | 0
1 | x2 | 1
1 | x3 | 1.4
1 | x4 | 2
2 | x1 | 3
2 | x2 | 10
2 | x3 | 12.4
2 | x4 | 22
I need a query that returns me the MAX value for each unique position value. Now, I am querying it with:
SELECT DISTINCT (position) AS p, (SELECT MAX(values) AS v FROM MYTABLE WHERE position = p) FROM MYTABLE;
It took me 1651 rows in set (39.93 sec), and 1651 rows is just a test for this database (it probably should have more then 1651 rows.
What am I doing wrong ? are there any better way to get it in a faster way ?
Any help is appreciated. Cheers.,
Use the GroupBy-Clause:
SELECT Position, MAX(VALUES) FROM TableName
GROUP BY Position
Also, have a look at the documentation (about groupby): http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
Try using the GROUP BY
clause:
SELECT position AS p, MAX(values) AS v
FROM MYTABLE
GROUP BY p;
try this
SELECT position AS p, MAX(`values`) AS v FROM MYTABLE
GROUP BY position
OUTPUT:
P | V
1 | 2
2 | 22
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.