mysql - Calculating the largest out of multiple averages - SQL -
i have table, contains number of cd entrys, complete names, price , genre. trying return average price genre, average price of "rock", "pop", "alternative rock", "electronica", & "electro house". after then trying have automatically display genre highest average price.
the table called "cd" table columns cd.id, cd.title, cd.price & cd.genre
i have tried using method shown below.. trying establish different averages 3 of genres..
select ((select avg(cdprice) cd cd.genre = 'rock') rock, (select avg(cdprice) cd cd.genre = 'pop') pop, (select avg(cdprice) cd cd.genre = 'electro') electro);
however might missing method, not overly familiar "as" command , correct usage.
rows (almost) easier columns. want first avg
price each genre:
select avg(cdprice) price, genre cd group genre
the second part filter 1 highest avg(cdprice)
. there's couple of different options here, , depends on requirements happens if 2 genres have equivalent price? want both or random? simple way latter order set , select first row:
select top(1) avg(cdprice) price, genre cd group genre order price desc
if want both rows in case of ties, first find max of set, , self-join find matches:
select price, genre ( --first table our avg price per genre select avg(cdprice) price, genre cd group genre ) avg join ( --second table maximum avg price select max(price) ( select avg(cdprice) price cd group genre ) avg2 ) max on --join on price find genres have maximum price avg.price = max.price
or, take advantage of having
clause write (arguably) little cleaner:
select avg(cdprice) price, genre cd group genre having avg(cdprice) = ( select max(price) (select avg(cdprice) price cd group genre) )
Comments
Post a Comment