mysql - Eliminate certain duplicated rows after group by -
with db:
chef(cid,cname,age),
recipe(rid,rname),
cooked(orderid,cid,rid,price)
customers(cuid,orderid,time,daytime,age)
[cid means chef id, , on]
given orders customers, need find each chef, difference between age , average of people ordered his/her meals. wrote following query:
select cid, ch.age - avg(cu.age) diff chef ch natural join cooked co,customers cu co.orderid = cu.orderid group cid
this solves problem, if assume customers has unique id, might not work,because 1 can order 2 meals of same chef , affect calculation.
now know can answered not exists i'm looking soultion includes group function (something similar wrote). far couldn't find (i searched , tried many ways, select distinct , manipulation in clause ,to "having count(distinct..)" )
edit: people asked exmaple. i'm coding using sqlfiddle , crashes alot, i'll try best:
cid | cuid | orderid | cu.age ----------------------------- 1 333 1 20 1 200 2 41 1 200 5 41 2 4 3 36
let's chef 1's age 50 . query give 50 - (20+40+40/3) = 16 , 2/3. althought should 50 - (20+40/2) = 20. (because guy id 200 ordered 2 recipes of our beloved chef 1.). assume chef 2's age 47. query result:
cid | diff ---------- 1 16.667 2 11
another edit: wasn't taught particular sql-query form.so have no idea differences between oracle's mysql's microsoft server's, i'm "freestyle" querying.(i hope in exam :o )
first, should write query as:
select cid, ch.age - avg(cu.age) diff chef ch join cooked co on ch.cid = co.cid join customers cu on co.orderid = cu.orderid group cid;
two different reasons:
natural join
bug waiting happen. list columns want used join, lest unexpected field or spelling difference affect results.- never use commas in
from
clause. use explicitjoin
syntax.
next, answer question more complicated. each chef, can average age of customers doing:
select cid, avg(age) (select distinct co.cid, cu.cuid, cu.age cooked co join customers cu on co.orderid = cu.orderid ) c group cid;
then, difference, need bring information in well. 1 method in subquery:
select cid, ( age - avg(cuage) ) diff (select distinct co.cid, cu.cuid, cu.age cuage, c.age cage chef c join cooked co on ch.cid = co.cid join customers cu on co.orderid = cu.orderid ) c group cid, cage;
Comments
Post a Comment