I've a table with SN and titles In the first query i do :
create or replace view AB as
select wrote.serial_number as SN, count(wrote.serial_number) as NumOfPapers
from wrote
group by wrote.serial_number;
and i DO get a view with SN and the count of the titles per SN than i want to get the ROW with the most titles (max of count) as : ID | max(count) so i do :
select AB.SN, max(AB.NumOfPapers)
from AB
but i get the max number of the counts with the first row person's SN (not the real SN with the most titles)
I have to use max() ... thanks for the suggestions using 'order by' but they are not relevant here
What am i doing wrong ?
Thanks !
6 Answers 6
I think you want something like this:
SELECT sn
FROM ab
ORDER BY NumOfPapers DESC
LIMIT 1
3 Comments
The reason you're only getting the first row's count of NumOfPapers is because you are also selecting the ab.serial number. So, I think this will give you what you're looking for:
select AB.SN, AB.NumOfPapers FROM AB order by AB.NumOfPapers desc limit 1;
1 Comment
create or replace view AB as
select wrote.serial_number as SN, count(wrote.serial_number) as NumOfPapers
from wrote
group by wrote.serial_number
ORDER by NumOfPapers DESC;
and
select AB.SN, AB.NumOfPapers from AB LIMIT 1
Comments
you are using NumOfPapers which is count of serial_number
select AB.SN, max(wrote.serial_number)
from AB, wrote
2 Comments
I think i got it figured :
create or replace view AB as
select wrote.serial_number as SN, count(wrote.serial_number) as NumOfPapers
from wrote
group by wrote.serial_number;
select AB.SN, AB.NumOfPapers
from AB
where AB.NumOfPapers = (select max(AB.NumOfPapers)
from AB)
Thank you all for your help, you really guided me there !
1 Comment
I believe your second query asks your database for every AB.SN from AB and the max(AB.NumOfPapers) Have you tried with a where statement?
select AB.SN, max(AB.NumOfPapers)
from AB
where AB.NumOfPapers = max(AB.NumOfPapers)
(I haven't tested this though, some adjustments might be needed)
select AB.SN, max(AB.NumOfPapers) from ABis not valid SQL. (though mysql will not complain about it). You forgot thegroup byclause.MAXfunction by itself does not require aGROUP BYclause, but one is required if you ask for other columns in theSELECTclause.SELECT MAX(NumOfPapers) FROM abis perfectly valid because you are asking for the result of an analytical function across the entire table.