Oracle-SELECT DENSE_RANK OVER(ORDER BY,SUM,OVER和PARTITION BY)

时间:2019-07-02 15:08:00

标签: sql oracle oracle11g

我有一个数据库,可以从两张表中获取很多,缺陷和数量。

在略微更改了名称并删除了一些我确定对该问题不重要的过滤器之后,当前正在运行的查询如下所示(在this answer的帮助下):

WITH subquery AS (
  SELECT * FROM (
    SELECT tbl2.lot
    FROM db.tbl1 tbl1, db.tbl2 tbl2
    WHERE tbl2.key = tbl1.key
    GROUP BY tbl2.lot
    ORDER BY Sum(tbl1.qtd) DESC, tbl2.lot
  ) WHERE ROWNUM <= 10
) SELECT tbl2.lot, tbl1.defect, tbl1.desc, Sum(tbl1.qtd)
FROM db.tbl1 tbl1, db.tbl2 tbl2, subquery
WHERE tbl2.lot = subquery.lot
  AND tbl2.key = tbl1.key
GROUP BY tbl2.lot, tbl1.defect, tbl1.desc
ORDER BY Sum(Sum(tbl1.qtd)) OVER (PARTITION BY tbl2.lot) DESC, Sum(tbl1.qtd) DESC, tbl2.lot, tbl1.defect, tbl1.desc

我正在尝试进一步改善查询,我得到了this solution来对其进行优化,但这是我所需要的,但是在结合两个答案时却出现了错误。

在我看来,解决方案应该是以下查询:

SELECT *
FROM (
  SELECT DENSE_RANK() OVER (ORDER BY Sum(Sum(tbl1.qtd)) OVER (PARTITION BY tbl2.lot) DESC, Sum(tbl1.qtd) DESC, tbl2.lot, tbl1.defect, tbl1.desc) rnk, tbl2.lot, tbl1.defect, tbl1.desc, Sum(tbl1.qtd)
  FROM db.tbl1 tbl1, db.tbl2 tbl2
  WHERE tbl2.key = tbl1.key
  GROUP BY tbl2.lot, tbl1.defect, tbl1.desc
  ORDER BY Sum(Sum(tbl1.qtd)) OVER (PARTITION BY tbl2.lot) DESC, Sum(tbl1.qtd) DESC, tbl2.lot, tbl1.defect, tbl1.desc
)
WHERE rnk <= 10
ORDER BY rnk

但是我收到错误It was not possible to add the table '('.(翻译)。

当我从查询中删除Sum(Sum(tbl1.qtd)) OVER (PARTITION BY tbl2.lot) DESC,中的SELECT DENSE_RANK() OVER(ORDER BY ...)部分时,它会运行并起作用,只是它不会按照我需要的方式对值进行排序。

我不确定问题是否可能是在另一个OVER中。我试图通过更换零件来找出原因,然后看看会发生什么,但找不到解决方法。

1 个答案:

答案 0 :(得分:0)

经过大量尝试,我仍然不确定是否可以在DENSE_RANK()的{​​{1}}内修复订单,但我确实找到了两者之间的解决方案。

OVER

它不如我尝试的解决方案好,但是比我以前的工作代码要好。 我所做的是将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 Sum(Sum(tbl1.qtd)) OVER (PARTITION BY tbl2.lot)中移出,然后将其添加为名称DENSE_RANK()