mysql - Synonyms, Outer Joins, Single Row String Functions -
how return order id’s , total sum of quantities each order in order details table. label total value "total qtys" , return orders had total quantities > 250 , sort 1 on total quantities highest lowest?
this mysql. assuming referring sum(qty)
schema / load data test
create table orders ( id int auto_increment primary key, custid int not null -- etc etc -- fk customer id ); create table orderdetails ( id int auto_increment primary key, orderid int not null, itemid int not null, qty int not null, -- etc etc -- fk items table not shown in example -- fk constraint orders table below: constraint fk_orddet_ords foreign key (orderid) references orders(id) ); insert orders (custid) values (1),(2),(3); insert orderdetails (orderid,itemid,qty) values (1,1,9),(2,1,190),(2,1,100),(3,1,255); -- below shows fk constraint fails faulty data (orderid 4 not exist) insert orderdetails (orderid,itemid,qty) values (4,1,9);
the query
if don't inr id 2 won't show (that if join qty>250). not there aren't smarter minds out there here mine:
select id,custid,qty (select o.id,o.custid,sum(d.qty) qty orders o join orderdetails d on d.orderid=o.id group o.id,o.custid) inr inr.qty>250 order qty desc +----+--------+------+ | id | custid | qty | +----+--------+------+ | 2 | 2 | 290 | | 3 | 3 | 255 | +----+--------+------+ 2 rows in set (0.05 sec)
Comments
Post a Comment