I have a database where I get lots, defects and quantities (from 2 tables).
After changing the names slightly and removing some filters which I made sure weren\'t import
After a lot of trying I still haven't figure out if it's possible to fix the order inside the DENSE_RANK()
's OVER
but I did found out a solution in between the two.
SELECT lot, def, qtd
FROM (
SELECT DENSE_RANK() OVER (ORDER BY qtd_lot DESC) rnk, lot, def, qtd
FROM (
SELECT tbl2.lot lot, tbl1.def def, Sum(tbl1.qtd) qtd, Sum(Sum(tbl1.qtd)) OVER (PARTITION BY tbl2.lot) qtd_lot
FROM db.tbl1 tbl1, db.tbl2 tbl2
WHERE tbl2.key = tbl1.key
GROUP BY tbl2.lot, tbl1.def
)
)
WHERE rnk <= 10
ORDER BY rnk, qtd DESC, lot, def
It's not as good as the solution that I was trying but it is better than my previous working code.
What I did was move the Sum(Sum(tbl1.qtd)) OVER (PARTITION BY tbl2.lot)
out of the DENSE_RANK()
and then add it with the name qtd_lot
.