加入和计算问题

时间:2012-02-14 23:08:39

标签: mysql sql join

好吧,经过3-4天试图解决这个问题后,我放弃了。 我开始只有一张桌子,但现在我已经改变了很多,所以我可以有两张桌子,我认为这会让像我这样的菜鸟更容易。 See my earlier post here

我没有在此处发布所有表格详细信息,而是提供了截图: Tables and expected result

我已经设法走得很远,但问题是我无法进行计算,不包括不应包含的批次。

我怎么能解决这个问题?我非常感谢你们给我们的帮助。 提前致谢

1 个答案:

答案 0 :(得分:1)

第一步:为详细信息表创建过滤器

SELECT
  MAX(id) AS id
FROM details
GROUP BY `concat`, `batch`

下一步:使用此查询详细信息表

SELECT * FROM details
WHERE id IN (
    SELECT
      MAX(id) AS id
    FROM details
    GROUP BY `concat`, `batch`
)

下一步:使用此派生表加入主表以获得最终结果

SELECT
  `master`.id AS id,
  `master`.plant AS plant,
  `master`.`code` AS `code`,
  COUNT(*) AS distinct_batches,
  SUM(filtereddetails.volume) AS total_vol,
  SUM(filtereddetails.`value`) AS total_val,
  SUM(filtereddetails.volume*filtereddetails.risk) AS risk_vol,
  SUM(filtereddetails.`value`*filtereddetails.risk) AS risk_val,
  MAX(filtereddetails.end_date-filtereddetails.start_date) AS max_date_diff
FROM
  `master`
  INNER JOIN (
    SELECT * FROM details
    WHERE id IN (
        SELECT
          MAX(id) AS id
        FROM details
        GROUP BY `concat`, `batch`
    )
  ) AS filtereddetails ON `master`.`concat`=filtereddetails.`concat`
GROUP BY
  `master`.`concat`