根据其他列的值检索组中的数据

时间:2009-09-18 06:27:41

标签: oracle oracle10g

我有一个包含以下列的表。

BoxNumber          Status
580                 4 
581                 4
582                 4
583                 4
584                 2
585                 2
586                 4
587                 4
588                 4
589                 4
590                 2
591                 2

我需要一个选择查询来获得以下输出。

StartingBoxNumber EndingBoxNumber    Status
580                     583           4
584                     585           2
586                     589           4
590                     591           2

2 个答案:

答案 0 :(得分:1)

您可以通过一次扫描表来获得结果,使用分析来定义连续行的“组”:

SQL> SELECT MIN(boxnumber), MAX(boxnumber), status
  2    FROM (SELECT boxnumber, status,
  3                 SUM(status_change) over(ORDER BY boxnumber) group_id
  4             FROM (SELECT boxnumber, status,
  5                           CASE
  6                              WHEN lag(status) over(ORDER BY boxnumber)
  7                                   = status
  8                               AND lag(boxnumber) over(ORDER BY boxnumber)
  9                                   = boxnumber - 1 THEN
 10                               0
 11                              ELSE
 12                               1
 13                           END status_change
 14                      FROM box))
 15   GROUP BY status, group_id
 16   ORDER BY 1;

MIN(BOXNUMBER) MAX(BOXNUMBER)     STATUS
-------------- -------------- ----------
           580            583          4
           584            585          2
           586            589          4
           590            591          2

答案 1 :(得分:0)

假设箱号始终是连续的:

SELECT  COALESCE(
        LAG(Boxnumber) OVER (ORDER BY BoxNumber),
        (
        SELECT  MIN(BoxNumber)
        FROM    mytable
        )) AS StartBoxNumber,
        BoxNumber AS EndBoxNumber,
        status
FROM    mytable qo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    mytable  qi
        WHERE   qi.boxnumber = qo.boxnumber + 1
                AND qi.status = qo.status
        )