简体   繁体   中英

rownum in Subquery

I was wondring why this doesn't work:

SELECT 
  (
    SELECT COALESCE(MAX(a.LaufNr),0) + TBL.Rownum
    FROM schemaB.PersonRelatedTbl A
    WHERE A.Persid = Tbl.Persid
  )
  , Tbl.Some_Other_Attributs
FROM schemaA.PersonRelatedTbl TBL 
WHERE ...

This + TBL.Rownum gives an error
why?

greets Auro

rownum is a pseudocolumn in a result set. It is not associated with any tables, and is the among the last things that get assigned (it happens after all sorting, etc).

It is possible that the row_number() function would be more useful for what you're doing, but, if you want the numbers to stay the same across all query invocations for each given row then you're going to have to store the numbers in the database (or use rowid , but, that's more like a serial number and is pretty ugly to show to end users). It's not really clear from your example what you expect rownum to be doing.

The TBL alias isn't used in the sub query but in the main query. ie

SELECT COALESCE(MAX(a.LaufNr),0) + TBL.Rownum
FROM schemaB.PersonRelatedTbl A
WHERE A.Persid = Tbl.Persid

is not a valid query.

Reading between the lines in the comments above, and your SQL, I would suggest reading up on Oracle's analytic functions.

http://www.orafaq.com/node/55

These are excellent for calculating things that typically need nested sub-queries that perform group functions - ie 'give me the running balance of X for each row', 'give me the rank of X out of the total set of data' or simply 'give me the total count of data'.

What makes them hard to grasp at first is that the syntax is complex, as they can do similar queries for partitions of your data set.

In your case you could probably use the COUNT(*) OVER () operation to get the 'height' from your other table.

Row num is per output row - not for every table

Why not try

SELECT 
  (
    SELECT COALESCE(MAX(a.LaufNr),0)
    FROM schemaB.PersonRelatedTbl A
    WHERE A.Persid = Tbl.Persid
  ) || rownum, Some_Other_Attributs
FROM schemaA.PersonRelatedTbl TBL 
WHERE ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM