简体   繁体   English

MySQL DISTINCT和COUNT查询

[英]Mysql DISTINCT and COUNT query

im having issues getting a query to output how i want, 即时通讯在获取查询以输出我想要的方式时遇到问题,

SELECT 
    `orders`.`item_id`, 
    `products`.`item_code`, 
    `products`.`item_name`, 
    `orders`.`quantity` 
FROM 
    `orders` 
    JOIN `products` ON `orders`.`item_id` = `products`.`id` 
    JOIN `suppliers` ON `products`.`supplier_ref` = `suppliers`.`supplier_ref` 
WHERE 
    `suppliers`.`id` = 159 
    AND `orders`.`order_status` = 'NOTED'

which is returning the results: 返回结果:

item_id item_code item_name            quantity
1271    RA001G    Green Mop Bucket 12L 2
1270    RA001     Blue Mop Bucket 12L  1
1270    RA001     Blue Mop Bucket 12L  1

but i would like it to bring back distinct item_id with the quantity added together how ever when i've tried to add distinct and count i end up only have one line returned. 但是我希望它带回与众不同的item_id,并且当我尝试添加与众不同并计数时,最终我只返回了一行。

If you want to sum up the quantities for same items, try grouping over item_id. 如果要汇总相同项目的数量,请尝试对item_id进行分组 Like this: 像这样:

SELECT 
    `orders`.`item_id`, 
    `products`.`item_code`, 
    `products`.`item_name`, 
    sum(`orders`.`quantity`) as quantity, 
FROM 
    `orders` 
    JOIN `products` ON `orders`.`item_id` = `products`.`id` 
    JOIN `suppliers` ON `products`.`supplier_ref` = `suppliers`.`supplier_ref` 
WHERE 
    `suppliers`.`id` = 159 
     AND `orders`.`order_status` = 'NOTED'
  GROUP BY `orders`.`item_id`, 
      `products`.`item_code`, 
      `products`.`item_name`

Please use group by clause 请使用分组方式

 SELECT 
`orders`.`item_id`, 
`products`.`item_code`, 
`products`.`item_name`, 
 sum(`orders`.`quantity`) as quantity
 FROM 
  `orders` 
   JOIN `products` ON `orders`.`item_id` = `products`.`id` 
   JOIN `suppliers` ON `products`.`supplier_ref` =   `suppliers`.`supplier_ref` 
WHERE 
 `suppliers`.`id` = 159 AND `orders`.`order_status` = 'NOTED'
group by 
 `orders`.`item_id`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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