自我加入问题,我想?

时间:2012-02-13 19:21:28

标签: mysql sql greatest-n-per-group

我有一张桌子(只能有一张),如下图所示。

它包含工厂代码,商品编号和与该文章相关的批次。

plant - code - batch - value - volume - added_date
A1      1000   A1      10      20       date
A1      2000   A7      20      15       date
A1      1000   A1      5       10       later than first A1 batch
A2      200    A8      10      9        date
A1      2000   A10     20      20       date

我如何能够像这样显示以下信息:对于每个工厂和代码,仅显示DISTINCT批次数和最新添加批次的数量(请注意plant A1中的代码1000正在显示只有10,因为这是最新添加的批次的数量。)

plant - code - batches - volume
  A1      1000   1         10     
  A1      2000   2         35
  A2      200    1         9

我早些时候从一个人那里得到了一些帮助,如果同一工厂的同一产品有两批具有相同编号的批次,我会尝试从最新批次中获取该批量的查询效果很好。

SELECT code, plant,
    COUNT(DISTINCT(batch)) as Batches,
    SUM(value) as TotalValue,
    SUM(volume) as TotalVolume,
    SUM(value * risk) as TotalRisk,
FROM lists 
GROUP BY code, plant

我想你可以通过一些连接和自我连接来做到这一点,但我不够熟练只能使用一个表:/

提前致谢!

编辑:嗯,实际上Adrian链接到的答案解决了所描述的问题......但是,似乎很难做到其他一切都与该解决方案一起工作。我只描述了我的“问题”的一部分,我认为足以自己解决剩下的问题。但是我错了。我不仅需要最新添加的批次和卷,还需要对批次执行一些SUM操作。我想我最好将数据放在两个不同的表中并从那里开始工作。

2 个答案:

答案 0 :(得分:0)

使用JOIN子查询可以通过MAX(added_date)检索卷:

SELECT
  l.code,
  l.plant,
  COUNT(DISTINCT l.batch) AS Batches,
  lvol.vol AS volume
FROM
  lists l JOIN (
    SELECT code, plant, volume AS vol FROM lists GROUP BY code, plant HAVING added_date = MAX(added_date)
  ) lvol ON l.code = lvol.code AND l.plant = lvol.plant AND l.volume = lvol.volume
GROUP BY l.code, l.plant

答案 1 :(得分:0)

SELECT  t.*,
        (SELECT  volume 
           FROM  lists
          WHERE  plant = t.plant
            AND  code  = t.code
          ORDER BY added_date DESC
          LIMIT 1   --Take the latest record for the plant & code
          ) AS volume                  
  FROM  (
            SELECT code, plant,
                COUNT(DISTINCT(batch)) as Batches,
                SUM(value) as TotalValue,
                SUM(value * risk) as TotalRisk
            FROM lists 
            GROUP BY code, plant
        ) AS t