1

I am normally working with MS SQL. I have a piece of code which I might have to translate to Oracle SQL. In this piece of code I update two variables for each row in order to find the max value of concurrent users.

My question is if it is possible to do the same as what is being done in the MS SQL code below in Oracle?

-- 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 に答える