Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select Order with highest sum of line items price

I have two tables in mysql :
Orders (id, orderName)
Order_item (id, partname, price, order_id)

Order_id in order item is foreign key to Order table.

How to select order with highest sum of order_item price?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

can you please advice me how to do it in oracle and mysql?

I try to do it with this query:

SELECT ord.* FROM ORDERS ord WHERE ID =  (Select  o.id from  ORDERS o
inner join order_item oi on o.id =oi.order_id
group by oi.id,ord.orderName
order by sum(oi.price) desc limit 1)

but it select order with highest price of order_item.price.

;

Note that select top 1 is not valid statement in mysql.

Is this correct solution ?:

SELECT ord.* FROM ORDERS ord WHERE ID =  (  Select  o.id from  ORDERS o
inner join order_item oi on o.id =oi.order_id group by o.id order by sum(oi.price) desc limit 1);

At least on Mysql server it runs. How to rewrite this to correct Oracle sql statement?

>Solution :

In Oracle:

SELECT o.id,
       MAX(o.ordername) AS ordername
FROM   "ORDER" o
       INNER JOIN Order_item oi
       ON (o.id = oi.order_id)
GROUP BY o.id
ORDER BY SUM(oi.price) DESC
FETCH FIRST ROW ONLY;

Note: ORDER is a reserved word and cannot be used as an unquoted identifier. Either use a quoted identifier (and always use the correct case) or change to a different identifier such as orders.

In MySQL:

SELECT o.id,
       MAX(o.ordername) AS ordername
FROM   Order o
       INNER JOIN Order_item oi
       ON (o.id = oi.order_id)
GROUP BY o.id
ORDER BY SUM(oi.price) DESC
LIMIT 1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading