繁体   English   中英

MySQL与group_concat和联接表求和

[英]Mysql sum with group_concat and join tables

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

我有三张桌子

product_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

productcontains_table

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

暂无
暂无

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

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