Mysql sum 与 group_concat 和连接表

标签 mysql sql group-by

我已经尝试解决这个问题大约几周了,但仍然没有答案 我想显示具有相同产品条形码的 inventory_table 的总数量,并显示其商品描述。

我有三张 table

产品表

ID| barcode | brand    | unit   | price
1 | 1111111 | Neozep   | Tablet | 5.50
2 | 2222222 | Biogesic | Syrup  | 7.50

库存表

ID| batch   | Total| barcode
1 | 5555555 | 100  | 1111111
2 | 6666666 | 500  | 1111111

产品包含表

ID| Name        | Amount | Type | barcode
1 | Paracetamol | 250    | mg   | 1111111
2 | Amoxicilin  | 20     | ml   | 1111111

输出应该是这样的

Barcode | Item Description                       | Price | Total Qty | Amount 
1111111 | Paracetamol 250 mg | Amoxicilin 20 ml  | P5.50 | 600       | P3300

我当前的Sql语句但这显然是错误的希望你们能帮助我 提前致谢

SELECT
GROUP_CONCAT(DISTINCT productcontains_table.name ,' ',
    productcontains_table.Amount,' ',
    productcontains_table.Type
    ORDER BY productcontains_table.IDno  SEPARATOR ' | ' ) AS ItemDescription,

    product_table.product_price AS Price,
    SUM(inventory_table.inventory_total) AS TotalQuantity

    product_table.price AS Price,
    SUM(inventory_table.total) AS TotalQuantity,
    product_table.price * SUM(inventory_table.total) AS TotalAmount

   FROM inventory_table
   JOIN product_table
   ON product_table.barcode = inventory_table.barcode
   JOIN productcontains_table
   ON productcontains_table.barcode = product_table.barcode

   GROUP BY inventory_table.barcode

最佳答案

修正了几个错别字:

SELECT inventory_table.barcode,
   GROUP_CONCAT(DISTINCT productcontains_table.name,' ', productcontains_table.Amount,' ', productcontains_table.Type SEPARATOR ' | ') AS ItemDescription,
   product_table.price AS Price,
   SUM(inventory_table.total)/ b.cnt AS TotalQuantity,
   product_table.price * SUM(inventory_table.total) / b.cnt AS Amount
FROM inventory_table
JOIN product_table ON product_table.barcode = inventory_table.barcode
JOIN productcontains_table ON productcontains_table.barcode = product_table.barcode
JOIN
( SELECT barcode,
       count(productcontains_table.name) AS cnt
  FROM productcontains_table )b ON b.barcode=product_table.barcode
GROUP BY inventory_table.barcode,
     product_table.price,
     inventory_table.barcode

http://sqlfiddle.com/#!9/2f372/37

关于Mysql sum 与 group_concat 和连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42630582/

相关文章:

c# - 当实例在多列上分组或分类时如何找到平均值?

sql - 在 ms-sql 2000 的 where 子句中使用别名列

python - 如何在Python中使用group-by函数保留列名?

mysql - 从重复数据中选择唯一数据的查询速度更快

ruby-on-rails - Rails - group_by

android - 如何在 Android 中编写 SQL 查询?

mysql - 如何在 Xampp 控制面板上启动 mysql?

mysql - 员工详细信息未正确显示

java - 如何从 mysql 触发器中捕获 sqlException 或信号消息

sqlalchemy:使用别名从多个连接中选择特定列