Oracle SQL Count或Sum以防查询?

时间:2018-10-01 21:17:23

标签: sql oracle count sum case

我在StackOverflow上研究了五个不同的线程,我觉得我已经接近了,但仍然没有雪茄。我的原始表有几个部分,每个部分有几行,每行有几个位置。我希望能够查询一个结果,该结果列出了节,行,位置,该行中一个以上的位置(较低的位置编号)以及该行中以下一个位置的位置(较大的位置)有多少位置。

这就是我所拥有的:

SELECT section, 
       row, 
       position AS P, 
       SUM(case when position < P then 1 else 0 end) AS Above, 
       SUM(case when position > P then 1 else 0 end) AS Below 
FROM OriginalTable 
GROUP BY section, row, position 
ORDER BY section, row, position

总和情况没有将P识别为位置,当我将P更改为数字时,总和就差了。

2 个答案:

答案 0 :(得分:2)

一种可能的解决方案是相关子查询,该查询获得count()的某节和某行的较低/较高位置。

SELECT ot1.section,
       ot1.row,
       ot1.position,
       (SELECT count(*)
               FROM originaltable ot2
               WHERE ot2.section = ot1.section
                     AND ot2.row = ot2.row
                     AND ot2.position > ot1.position) above,
       (SELECT count(*)
               FROM originaltable ot2
               WHERE ot2.section = ot1.section
                     AND ot2.row = ot2.row
                     AND ot2.position < ot1.position) below
      FROM originaltable ot1
      ORDER BY ot1.section,
               ot1.row,
               ot1.position;

另一人正在使用count()的窗口版本。

SELECT ot1.section,
       ot1.row,
       ot1.position,
       count(*) OVER (PARTITION BY ot1.section,
                                   ot1.row
                      ORDER BY ot1.position
                      RANGE BETWEEN CURRENT ROW
                                    AND UNBOUNDED FOLLOWING) - 1 above
       count(*) OVER (PARTITION BY ot1.section,
                                   ot1.row
                      ORDER BY ot1.position
                      RANGE BETWEEN UNBOUNDED PRECEDING
                                    AND CURRENT ROW) - 1 below
      FROM originaltable ot1
      ORDER BY ot1.section,
               ot1.row,
               ot1.position;

答案 1 :(得分:2)

我只会使用row_number()

SELECT section, row, position AS P, 
       ROW_NUMBER() OVER (PARTITION BY section, row ORDER BY position ASC) - 1 as Above,
       ROW_NUMBER() OVER (PARTITION BY section, row ORDER BY position DESC) - 1 as Below
FROM OriginalTable
ORDER BY section, row, position;

如果您有重复项,那么这个问题会比较棘手(尽管GROUP BY可以解决这个问题)。您可能需要DENSE_RANK()而不是ROW_NUMBER()