简体   繁体   中英

mysql distinct manufacturer,count of 2 other columns and sum of value

Afternoon,

I have a couple of tables in mysql The first holds the ticket information and status of ticket The second holds the items and costs for each item.

Each ticket can have multiple items which are stored into the items table.

example table 1

Ticket id    Manufacturer    status
 102           man-A           10
 103           man-A           20
 104           man-A           10
 105           man-C           10
 106           man-B           20

example table 2

Ticket id     Item           Price
 102           item_a         100.00
 103           item_a         100.00
 103           item_b         110.00
 103           item_c         115.00
 104           item_c         115.00
 105           item_b         110.00
 106           item_a         100.00
 106           item_c         115.00

now on a quick stats page i need to show.

 Manufacturer      Qty(status 10)  Qty(status 20)   Value
  man-A             2                1               530.00
  man-B             0                1               225.00
  man-C             1                0               110.00

If there are no tickets with status 10 or status 20 i do not need to show that manufacturer.

I would like to do 1 mysql request to get the stats i need to show.

Many Thanks

Try this with join and using SUM()

SELECT 
t1.Manufacturer,
SUM(t1.status =10) `Qty(status 10)`,
SUM(t1.status =20) `Qty(status 20)`,
SUM(t2.price) `Value`
FROM table1 t1
JOIN table2 t2 ON (t1.`Ticket id` =t1.`Ticket id`)
GROUP BY t1.Manufacturer 

Fiddle Demo

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