php - SQL query finding maximum for two joint tables by category -
i'm wondering how find maximum of each category if have join 2 tables.
i have 2 tables. restaurant possesses name, address, cuisine, county (area) , rid (restaurant id).
i have inspection has rid, idate (date of inspection) , totalscore (the inspection score restaurant).
say have display cuisine of restaurant, name of restaurant, address , totalscore (from inspection class). have list best restaurant each cuisine in particular county ('cobb' in code) , date of inspection must in 2015. instance, chinese cuisine "beijing central" totalscore of 99 (out of 100).
so far have code:
select distinct cuisine, name,address, max(totalscore) restaurant r join inspection on r.rid = i.rid county = 'cobb' , year(idate) = 2015 group cuisine, name, adddress;
while gets me close, keep getting duplicate copies. instance, lists 2 different chinese restaurants instead of choosing best one.
i'm trying improve sql coding style if has solution or best practices, appreciated!
----edit--- here of sample data database when join inspection , restaurant on rid.
rid | idate | totalscore | name | county | street | cuisine | +-----+------------+------------+-------------------+--------+---------------------+----------+ | 13 | 2015-01-04 | 90 | heirloom | cobb | 2243 akers mill rd | american | | 14 | 2015-01-27 | 49 | china moon | cobb | 2810 paces ferry rd | chinese | | 14 | 2015-02-27 | 83 | china moon | cobb | 2810 paces ferry rd | chinese | | 15 | 2015-03-27 | 77 | house of chan | cobb | 2469 cobb pkwy | chinese | | 16 | 2015-03-18 | 47 | love sushi | cobb | 2086 cobb pkwy | japanese | | 16 | 2015-04-18 | 87 | love sushi | cobb | 2086 cobb pkwy | japanese | | 17 | 2015-05-18 | 90 | douceur de france | cobb | 277 s marietta pkwy | french | | 18 | 2015-05-22 | 59 | swapna | cobb | 2655 cobb pkwy | indian | | 18 | 2015-06-22 | 75 | swapna | cobb | 2655 cobb pkwy | indian | | 19 | 2015-06-18 | 32 | mezza luna | cobb | 1669 spring rd | italian | | 19 | 2015-07-18 | 98 | mezza luna | cobb | 1669 spring rd | italian |
desired result like
indian: swapna : 75 chinese : china moon : 83 italian : mezza luna : 98 ...etc etc
it great if can create sql fiddle. if understand correctly want select max value each group (cuisine). should here how that.
here how query like:
select r.cuisine, r.name, r.address, i.totalscore restaurant r join inspection on r.rid = i.rid county = 'cobb' , year(idate) = 2015 , totalscore = (select max(i1.totalscore) from restaurant r1 join inspection i1 on r1.rid = i1.rid r.cuisine = r1.cuisine);
hope work, couldn't test because didn't provide data in question...
gl!
edit hi edit in question try create 2 table use in query , test it, , query forks fine... here sql fiddle can check scenario , add data can tune query if needed.
Comments
Post a Comment