简体   繁体   中英

how to get the number of items and cost sum ordered per order in mysql

i have two tables

order:

order_id |  order_date | order_by
----------------------------------
1          2018-01-05    suraj    
2          2018-01-06    sumanta

order_detail:

order_detail_id  | order_id  |  item_id  | item_cost
-----------------------------------------------------
1                     1           23         100    
2                     1           27         200    
3                     2           16         300    
4                     2           17         100    
5                     2           10         400

How do i get this data from above tables in mysql

order_id  |  order_date  | order_by   | no_of_item  | order_cost
----------------------------------------------------------------
1           2018-01-05      suraj           2           300    
2           2018-01-06      sumanta         3           700

Join your two tables, and aggregate with a GROUP BY.

SELECT t1.order_id, t1.order_date, t1.order_by, count(*) as no_of_items, sum(t2.item_cost) as order_cost
FROM order t1
    INNER JOIN order_detail t2
        ON t1.order_id = t2.order_id
GROUP BY t1.order_id, t1.order_date, t1.order_by;
SELECT o.order, o.order_date, o.order_by, COUNT(*), SUM(od.item_cost)
FROM order o JOIN order_detail od ON(o.order_id=od.order_id)
GROUP BY o.order_id, o.order_date, o.order_by;

I feel like I'm doing somebody's homework

Using SQL query.

SELECT o.order_id, o.order_date, o.order_by, 
COUNT(*) as no_of_item, SUM(od.item_cost) as order_cost 
FROM order o INNER JOIN order_detial od ON o.order_id = od.order_id
GROUP BY o.order_id, o.order_date, o.order_by;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM