Order Oracle query by SUM without selecting the SUM

限于喜欢 提交于 2019-12-02 08:16:03

问题


I have a table somewhat like the following one:

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

I want to sum the quantities where the lot and defect are equal between rows and then order the lot by the sum of its quantity (lot3=9+5+5=19, lot4=12, lot1=7+2=9, lot2=4), then the quantity (inside each lot), and then the defect.

So it should result in the following:

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

The closest I can think of is the following query:

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

Which results in the following:

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

回答1:


Your question seems to be about ordering the results. The solution is to use window functions in 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;


来源:https://stackoverflow.com/questions/56850744/order-oracle-query-by-sum-without-selecting-the-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!