通过SUM排序Oracle查询,而无需选择SUM

时间:2019-07-02 10:46:18

标签: sql oracle oracle11g odbc

我有一张类似于以下表格的表格:

 lot   |  defect  |  quantity
-------+----------+-----------
 lot1  |  c       |  7
 lot1  |  c       |  2
 lot3  |  e       |  5
 lot3  |  b       |  9
 lot3  |  a       |  5
 lot2  |  d       |  4
 lot4  |  c       |  12
 ...   |  ...     |  ...

我想对两行之间的批次和缺陷相等的数量求和,然后按其数量的总和排序(批次3 = 9 + 5 + 5 = 19,批次4 = 12 ,lot1 = 7 + 2 = 9,lot2 = 4),然后是数量(在每手内部),然后是缺陷。

因此它应该导致以下结果:

 lot   |  defect  |  SUM(quantity)
-------+----------+----------------
 lot3  |  b       |  9
 lot3  |  a       |  5
 lot3  |  e       |  5
 lot4  |  c       |  12
 lot1  |  c       |  9
 lot2  |  d       |  4
 ...   |  ...     |  ...

我能想到的最接近的是以下查询:

SELECT lot, defect, SUM(quantity)
FROM table
GROUP BY lot, defect
ORDER BY SUM(quantity), lot, defect

结果如下:

 lot   |  defect  |  SUM(quantity)
-------+----------+----------------
 lot4  |  c       |  12
 lot1  |  c       |  9
 lot3  |  b       |  9
 lot3  |  a       |  5
 lot3  |  e       |  5
 lot2  |  d       |  4
 ...   |  ...     |  ...

1 个答案:

答案 0 :(得分:3)

您的问题似乎与排序结果有关。解决方案是在ORDER BY中使用窗口函数:

SELECT lot, defect, SUM(quantity)
FROM table
GROUP BY lot, defect
ORDER BY SUM(SUM(quantity)) OVER (PARTITION BY lot) DESC,
         lot, SUM(quantity) DESC, defect;