连接表并对每个表执行聚合

时间:2015-02-13 17:51:31

标签: mysql sql

我有以下表格:

table part_list:

part_number | description | type
100           blablabla     blabla

table part_list_supplier:

part_id | artikel
100       100100
100       200100

我有这个问题:

select part_list.part_number, part_list.description, part_list.type, group_concat(coalesce(part_list_supplier.artikel, "nothing")) as "artikel"
from part_list 
left join part_list_supplier on (part_list.part_number = part_list_supplier.part_id)
group by part_list.part_number;

这是结果:

part_number | description | type   | artikel
100           blablablabla  blabla   100100,200100

但是我希望显示每个部分的总库存量。餐桌收据:

Number |  import 
100     5   
100     10
表销售:

Number | sold 
100     5

这是我对一个表的查询:

SELECT SUM(sold) AS sold
 FROM sales WHERE number = '".$partnumber.”'

但我想计算每个数字的库存,并且必须在其他结果后面显示。 完整的结果:

part_number | description | type   | artikel            | stock
100           blablablabla  blabla   100100,200100        10

股票应为10,因为进口总数为15(5 + 10),销售总数为5。

2 个答案:

答案 0 :(得分:1)

我把它分成几块来解决它。我开始编写两个查询,一个计算总收据,另一个计算总销售额:

SELECT r.number, SUM(r.import) AS totalIn
FROM receipt r
GROUP BY r.number;

SELECT s.number, SUM(s.sold) AS totalOut
FROM sales s
GROUP BY s.number;

然后,我使用它们作为联接的两个子查询来获取股票:

SELECT r.number, totalIn - totalOut AS stock
FROM(
  SELECT r.number, SUM(r.import) AS totalIn
  FROM receipt r
  GROUP BY r.number) r
JOIN(
  SELECT s.number, SUM(s.sold) AS totalOut
  FROM sales s
  GROUP BY s.number) s ON s.number = r.number;

一旦我确认这给了正确的库存,我就可以将这些子查询包含在原始查询中以构建它:

SELECT pl.part_number, pl.description, pl.type, 
    GROUP_CONCAT(COALESCE(pls.artikel, "Nothing.")) AS artikel,
    r.totalIn - s.totalOut AS stock
FROM part_list pl
LEFT JOIN part_list_supplier pls ON pls.part_id = pl.part_number
JOIN(
  SELECT number, SUM(import) AS totalIn
  FROM receipt
  GROUP BY number) r ON r.number = pl.part_number
JOIN(
  SELECT number, SUM(sold) AS totalOut
  FROM sales
  GROUP BY number) s ON s.number = r.number
GROUP BY pl.part_number;

以下是SQL Fiddle示例。

答案 1 :(得分:0)

我可能无法正确理解您的问题,但您不能只将sum(sales.sold)添加到您的select语句并加入sales表吗? E.g:

select part_list.part_number, part_list.description, part_list.type, group_concat(coalesce(part_list_supplier.artikel, "nothing")) as "artikel", sum(sales.sold)
from part_list 
left join part_list_supplier on (part_list.part_number = part_list_supplier.part_id)
left join sales on (part_list.part_number = sales.number
group by part_list.part_number;