问题
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