最小值和最大值--Oracle

时间:2014-05-06 09:17:18

标签: sql database oracle

尝试获得此输出:

尝试在Oracle 8i中获取此输出:

column1 |time
________|_______
  ABC   | 00:00:01
  END   | 01:00:03
  123   | 00:00:04
  END   | 01:00:07
  ABC   | 00:00:08
  END   | 01:00:09
  ABC   | 00:00:10
  END   | 01:00:10

使用另一个查询的输出

   column1  |starttime  |endtime     | ID
    ________|___________|___________ |
      ABC   | 00:00:01  |  01:00:01  | 1
      ABC   | 00:00:02  |  01:00:02  | 1
      ABC   | 00:00:03  |  01:00:03  | 1
      123   | 00:00:04  |  01:00:04  | 2
      123   | 00:00:05  |  01:00:05  | 2
      123   | 00:00:06  |  01:00:06  | 2
      123   | 00:00:07  |  01:00:07  | 2
      ABC   | 00:00:08  |  01:00:08  | 3
      ABC   | 00:00:09  |  01:00:09  | 3
      ABC   | 00:00:10  |  01:00:10  | 4

此查询仅获取starttime列的最小值和最大值:

SELECT (
  CASE
    WHEN n.n = 1
    THEN column1
    ELSE 'END'
  END) AS column1,
  (
  CASE
    WHEN n.n = 1
    THEN firsttime
    ELSE lasttime
  END) AS "time"
FROM
  (SELECT column1,
    id,
    MIN(starttime) AS firsttime,
    MAX(starttime) AS lasttime
  FROM t
  GROUP BY column1,
    id
  ) t
CROSS JOIN
  (SELECT 1 AS n FROM dual
  UNION ALL
  SELECT 2 FROM dual
  ) n
ORDER BY id,
  column1,
  n.n;

现在我有另一个名为endtime的列,我想知道如何考虑此列并从此列中获取END值?由于n.n 1只有ID的一条记录,我正在努力。

1 个答案:

答案 0 :(得分:0)

尝试使用以下查询,

with  DUMMYDATA AS
(    
SELECT 'ABC' COL1,  '00:00:01' STARTTIME, '01:00:01' ENDTIME, '1' ID FROM DUAL
UNION
SELECT 'ABC' COL1,  '00:00:02' STARTTIME, '01:00:02' ENDTIME, '1' ID FROM DUAL
UNION
SELECT 'ABC' COL1,  '00:00:03' STARTTIME, '01:00:03' ENDTIME, '1' ID FROM DUAL
UNION
SELECT '123' COL1,  '00:00:04' STARTTIME, '01:00:04' ENDTIME, '2' ID FROM DUAL
UNION
SELECT '123' COL1,  '00:00:05' STARTTIME, '01:00:05' ENDTIME, '2' ID FROM DUAL
UNION
SELECT '123' COL1,  '00:00:06' STARTTIME, '01:00:06' ENDTIME, '2' ID FROM DUAL
UNION
SELECT '123' COL1,  '00:00:07' STARTTIME, '01:00:07' ENDTIME, '2' ID FROM DUAL
UNION
SELECT 'ABC' COL1,  '00:00:08' STARTTIME, '01:00:08' ENDTIME, '3' ID FROM DUAL
UNION
SELECT 'ABC' COL1,  '00:00:09' STARTTIME, '01:00:09' ENDTIME, '3' ID FROM DUAL
UNION
SELECT 'ABC' COL1,  '00:00:10' STARTTIME, '01:00:10' ENDTIME, '4' ID FROM DUAL
) 
SELECT  * FROM
(
    SELECT COL1, MIN(STARTTIME) TIMEDATA, ID FROM DUMMYDATA 
    GROUP BY COL1, ID
    UNION ALL
    SELECT 'END', MAX(ENDTIME) TIMEDATA,ID FROM DUMMYDATA
    GROUP BY COL1, ID
)
ORDER BY ID, TIMEDATA