1

我通常使用 MS SQL。我有一段代码可能需要翻译成 Oracle SQL。在这段代码中,我为每一行更新了两个变量,以便找到并发用户的最大值。

我的问题是,是否可以像下面在 Oracle 的 MS SQL 代码中所做的那样做同样的事情?

-- The creation of this test table is not relevant to my question.
-- It is just there to make a working example
SELECT {ts '2012-09-03 10:12:00'} AS eventTime, 1 AS change
INTO #EVENTS
UNION ALL SELECT {ts '2012-09-03 10:24:00'}, 1
UNION ALL SELECT {ts '2012-09-03 10:25:00'}, 1
UNION ALL SELECT {ts '2012-09-03 11:02:00'}, -1
UNION ALL SELECT {ts '2012-09-03 11:25:00'}, 1
UNION ALL SELECT {ts '2012-09-03 11:34:00'}, 1
UNION ALL SELECT {ts '2012-09-03 12:15:00'}, -1
UNION ALL SELECT {ts '2012-09-03 13:50:00'}, -1
UNION ALL SELECT {ts '2012-09-03 14:20:00'}, -1
UNION ALL SELECT {ts '2012-09-03 14:44:00'}, -1

DECLARE @count int, @maxUsers int
SET @count = 0
SET @maxUsers = 0

-- This part is what is in question. Can you do something similar in Oracle?
-- Having calculation done for each row and store it in a variable for
-- the next row.
SELECT
    @count = @count + change,
    @maxUsers = CASE WHEN @count > @maxUsers THEN @count ELSE @maxUsers END
FROM #EVENTS
ORDER BY eventTime ASC

PRINT @maxUsers -- Prints the value 4

DROP TABLE #EVENTS
4

2 回答 2

1

Oracle 具有可用于获取诸如运行总计之类的分析功能。

SELECT MAX(CURRENTUSERS) FROM
(
  SELECT SUM(CHANGE) OVER (ORDER BY eventTime) AS CURRENTUSERS 
  FROM EVENTS
)
于 2012-09-03T14:35:54.657 回答
0

是的,你可以。使用 WITH 子句替换 #EVENTS,摆脱 DROP 并使用 select into 子句将其放入单个 SQL 语句中。为了进行 PRINT,请使用 dbms_output.put_line。我认为 ORDER BY 将不起作用,因此您必须使用 ROWNUMBER

于 2012-09-03T14:25:02.713 回答