1

我有来自 2 个表 Notes(左)和扫描(右)的以下数据:

在此处输入图像描述

想象一下,拣货员和打包员都各不相同,就像您可以拥有的一样JOHN, JANE

我需要一个这样输出的查询:

在给定的date range

Name - Picked (units) - Packed (units)
MASI - 15 - 21
JOHN - 21 - 32

等等

我什至不知道如何开始,任何提示都会有所帮助,谢谢。

4

2 回答 2

1
SELECT name, SUM(nbPicked) Picked, SUM(nbPacked) Packed
FROM
(SELECT n.Picker name, SUM(n.Units) nbPicked, 0 nbPacked 
FROM Notes n
INNER JOIN scans s ON s.PickNote = n.Number
--WHERE s.ProcessedOn BETWEEN x and y
GROUP BY n.Picker

UNION ALL

SELECT n.Packer name, 0 nbPicked, SUM(n.Units) nbPacked
FROM Notes n
INNER JOIN scans s ON s.PickNote= n.Number
--WHERE s.ProcessedOn BETWEEN x and y
GROUP BY n.Packer)

GROUP BY name;
于 2012-06-14T09:46:14.460 回答
1

如果没有单独列出每个 Picker/Packer 的“工人”,我认为你需要这样的东西......

SELECT
      CASE WHEN action.name = 'Picker' THEN scans.Picker ELSE scans.Packer END  AS worker,
  SUM(CASE WHEN action.name = 'Picker' THEN notes.Units  ELSE 0            END) AS PickedUnits,
  SUM(CASE WHEN action.name = 'Packer' THEN notes.Units  ELSE 0            END) AS PackedUnits
FROM
  notes
INNER JOIN
  scans
    ON scans.PickNote = notes.Number
CROSS JOIN
(
            SELECT 'Picker' AS name
  UNION ALL SELECT 'Packer' AS name

)
  AS action
GROUP BY
  CASE WHEN action.name = 'Picker' THEN scans.Picker ELSE scans.Packer END

(这实际上只是@RaphaëlAlthaus 与我同时发布的答案的代数重新安排。两者都用于UNION分别计算 Picker 值和 Packer 值。如果您有单独的索引scans.Pickerscans.Packer那么我会期待我的可能是最慢的。如果您没有这两个索引,那么我希望我的索引最快。我建议创建索引并在真实数据集上进行测试。)

编辑

实际上,我建议完全更改扫描表;规范化它。

  • 您的去规范化集每个 PickNote 有一行,带有字段pickerpacker.
  • 一个规范化的集合每个 PickNote 将有两行,其中包含字段roleworker.


  id  | PickNote | Role | Worker
------+----------+------+--------
  01  | PK162675 | Pick |  MASI
  02  | PK162675 | Pack |  MASI
  03  | PK162676 | Pick |  FRED
  04  | PK162676 | Pack |  JOHN

这允许您创建简单的索引和简单的查询。

您最初可能会拒绝额外不必要的行,但它会产生更简单的查询、更快的查询、更好的可维护性、更高的灵活性等。

简而言之,这种标准化可能会花费一些额外的空间,但它会永远回报红利。

于 2012-06-14T09:46:14.740 回答