【问题标题】:How to sum in mysqlmysql中如何求和
【发布时间】:2022-12-14 09:25:05
【问题描述】:

我在 mySQL 中有这个查询,我想对每个医生的线产品求和,但我不知道该怎么做。

use avant_medical;

select 
sales.doctor_id as DoctorID,
line_products.id as LineProductID,
line_products.name as LineProductName


from `doctors` 
inner join `sales` on `doctors`.`id` = `sales`.`doctor_id` 
inner join `inventories` on `sales`.`id` = `inventories`.`sale_id`
inner join `products` on `inventories`.`product_id` = `products`.`id`
inner join `line_products` on `products`.`lineProduct_id` = `line_products`.`id`


order by `doctors`.`id` asc;

 
lPID= lineProductID
|DrID|lPID |
| -- | ----|
| 1  | 7   |
| 1  | 6   |
| 1  | 6   |
| 1  | 7   |
| 1  | 7   |
| 1  | 7   |
| 1  | 6   |

This is how I want:

Doctor 1
lineID | quantity
  7    |    4
  6    |    3

我只在 mySQL 中尝试这个查询

【问题讨论】:

  • 您需要提供架构以显示数据的存储方式
  • 看起来你想要数数不是和但还不清楚。示例数据将帮助我们帮助您。

标签: mysql


【解决方案1】:

您要查找的关键字是count,而不是sum。求和会把每个 lineProductID 加起来,就好像它们是常规数学值一样,而计数会加起来找到给定的 lineProductID 的次数。

select 
    sales.doctor_id as DoctorID,
    line_products.id as LineProductID,
    line_products.name as LineProductName,

-- We count the number of occurrences of each line_product.id
    COUNT(line_products.id) as LineProductQty

from `doctors` 
    inner join `sales` on `doctors`.`id` = `sales`.`doctor_id` 
    inner join `inventories` on `sales`.`id` = `inventories`.`sale_id`
    inner join `products` on `inventories`.`product_id` = `products`.`id`
    inner join `line_products` on `products`.`lineProduct_id` = `line_products`.`id`

-- Never forget to properly GROUP your aggregate functions, such as COUNT() or SUM()!
GROUP BY sales.doctor_id, line_products.id, line_products.name

order by `doctors`.`id` asc;

由于您没有提供完整的模式来测试这个,I made a small, very artificial demo,但应该代表上面的查询是如何工作的。

【讨论】:

    猜你喜欢
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多