Select a column from an inner select statement

On my oracle 10g running on solaris, I am running this little query that gives me
the right results (I needed one more column and not able to get to it, hence looking for some ideas here)
Select a.othtype, a.date_from, a.date_to,b.process
from bio_plan_other a,
bio b,
Where a.bkey = b.bkey
and a.date_from <
(Select min(f.edate)
from bio_service f
where f.bkey = a.bkey) ;
In the inner select table bio_service, I have an additional column called service_name. Hence for the min(f.edate), there is a corresponding service_name.
How do I get that service_name in my topmost SELECT statement ?
In other words, I wanted to do something like...
Select a.othtype, a.date_from, a.date_to,b.process,f.service_name
from bio_plan_other a,
bio b,
Where a.bkey = b.bkey
and a.date_from <
(Select min(f.edate)
from bio_service f
where f.bkey = a.bkey) ;
But this gives me,
ORA-00904 : f.service_name : invalid identifier
Thanks

Hi
Not knowing your datamodel, but you probably have more service names per date, so did you try this?
WITH t_bio_service AS (SELECT b2.bkey, b2.min_edate, b.service_name
                         FROM bio_service b
                            , (SELECT MIN(edate) min_edate, bkey
                                 FROM bio_service
                                GROUP BY bkey) b2
                        WHERE b2.bkey = b.bkey
                          AND b2.min_edate = b.edate)
SELECT a.othtype, a.date_from, a.date_to,b.process, t.service_name
  FROM bio_plan_other a,
       bio b,
       t_bio_service t
WHERE a.bkey = b.bkey
   AND t.BKEY = b.bkey
   AND a.date_from < t.min_edateHope this helps.
Regards Auke

Similar Messages

  • Retrieving multiple values from one column in SELECT statement

    Hi,
    I have a slight dilemma in that I'm trying to pull down all the values from a column from a select statement that includes some JOINS in it.
    If I run the query at the SQL Plus prompt, it pulls back all the values/rows.
    When I run the select (and prepared ) statement in my JSP, it only pulls back one of the 4 values I'm trying to retrieve.
    e.g.
    at the DB level :
    SELECT role_name, CC_ID FROM votetbl a
    INNER JOIN APPROVERS b ON
    a.BUSVP = b.BUSVP AND
    a.BRANCH = b.BRANCH
    WHERE CC_ID = 1688this will return:
    ROLE_NAME CC_ID
    ops 1688
    ops 1688
    comply 1688
    legal 1688
    comply 1688
    When run in my JSP, like so:
    String primID3a = request.getParameter("primID");
    Statement stmtovoter = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    String prepvotSQL = "SELECT role_name, CC_ID FROM votetbl a INNER JOIN APPROVERS b ON a.BUSVP = b.BUSVP AND " +
                         "a.BRANCH = b.BRANCH WHERE CC_ID = ?";
    PreparedStatement prepvotstmt = connection.prepareStatement(prepvotSQL);
    prepvotstmt.setString(1, primID3a);
    ResultSet rest3 = prepvotstmt.executeQuery();
    rest3.next();
    String votecat = rest3.getString(1);
    out.println("Vote category: "+votecat);I only get ops returned.
    Do I need to run an enumerator? Or reqest.getParameterValues or use a while statement around the results set?
    Any feedback and direction here is welcomed!
    Thanks!

    Actually, I tried looping and still only get 1, but returned several times.
    i.e.
    PreparedStatement prepvotstmt = connection.prepareStatement(prepvotSQL);
    prepvotstmt.setString(1, primID3a);
    ResultSet rest3 = prepvotstmt.executeQuery();
    rest3.next();
    String votecat = rest3.getString(1);
    while (rest3.next()) {
    out.print("category roles "+votecat);
    }then I get returned the following:
    admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admin
    like so.
    Where as at the DB level I get
    ROLE_NAME CC_ID
    admin 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    risk 1688
    comply 1688
    legal 1688
    legal 1688
    ops 1688
    comply 1688
    Maybe the while should go around the getString(1) designation? But I was thinking I'd tried that and gotten invalid cursor error
    Something is definitely amiss, between the prepared statement in the servlet and the SELECT statement at the DB level.
    I can totally hardcode the statement in the servlet or JSP and it will return one value potentially several times, but only one.
    Other times, it will not return a value at all, even though one resides in the db.
    Yet go to the DB/SQL Plus prompt and it returns perfectly. I can simply copy and paste the SELECT statement from the out.print line I made and it works like a champ in SQL Plus. Any ideas why the same exact thing cannot return the proper values within the servlet/JSP?
    Yeeeeeeesh!!! : (
    Message was edited by:
    bpropes20

  • How can I select columns from a table EMP, using Select statement?.

    Hi Friends,
    How can I select columns from a table EMP?.
    I want to select columns of EMP table, using select statement.
    Please reply me urgently.
    Shahzad

    Something like this:
    scott@DBA> select empno,ename,job from emp;
         EMPNO ENAME      JOB
          7369 SMITH      CLERK
          7499 ALLEN      SALESMAN
          7521 WARD       SALESMAN
          7566 JONES      MANAGER
          7654 MARTIN     SALESMAN
          7698 BLAKE      MANAGER
          7782 CLARK      MANAGER
          7788 SCOTT      ANALYST
          7839 KING       PRESIDENT
          7844 TURNER     SALESMAN
          7876 ADAMS      CLERK
          7900 JAMES      CLERK
          7902 FORD       ANALYST
          7934 MILLER     CLERK
    14 rows selected.Check the documentation:
    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#sthref9697
    Message was edited by:
    Delfino Nunez

  • Merge statement - update multiple columns from a single sub-select

    Is it possible to write in 10gR2, a MERGE statement, with UPDATE for multiple columns from a single sub_select?
    like this:
    MERGE INTO tableA
    using ( select * from temp) tmp
    on( tableA. col1 = tmp.col1)
    when matched then
    update set  ( tableA.col5,
                       tableA.col6,
                       tableA.col7) = ( select sum(col2), sum(col3), sum(col5)
                                                                                 from tableX
                                                                                where tableX.col1 = tableA.col1...)

    Hi,
    The USING clause is not a sub-query, so it can't reference columns from tables that are not in it.
    Include tableA in the USING clause if you really need to refer to it there. (It's not obvious that you do.)
    As always, it helps if you post:
    (1) The version of Oracle (and any other relevant software) you're using
    (2) A little sample data (just enough to show what the problem is) from all the relevant tables
    (3) The results you want from that data (In the case of a DML statement, such as MERGE, this will be the state of the tables when everything is finished.)
    (4) Your best attempt so far (formatted)
    (5) The full error message (if any), including line number
    Executable SQL statements (like "CREATE TABLE AS ..." or "INSERT ..." statements) are best for (2).
    If you can present your problem using commonly available tables (for example, tables in scott schema, or views in the data dictionary), then you can omit (2).
    Formatted tabular output is okay for (3).

  • How do I group by only one column in a SELECT statement?

    Hi everyone,
    Here is my novice question:
    I would like to run a query where I select (display) several columns from my table, yet group (categorize) by one of these columns.
    For example:
    SELECT A, B, COUNT(A)
    FROM TableX
    GROUP BY A
    I realize now that this is not valid. My first question is why? Doesn't it make sense that you would want to group by only one of the columns? To me, it seems natural that you would most often want to categorize by one attribute, which is why it seems odd that this is not valid. I realize that I can remove column B, but I do want to display that info. I could also change the last statement to GROUP BY A, B to avoid errors, but this will also not display what I am looking for.
    In addition to understanding why Oracle is set up this way, I guess I also need to know how I can legally accomplish this query, grouping by A but also displaying the values of B.
    Thank you very much for your help!
    Holly

    Hi everyone,
    Thank you for your responses... very interesting and useful. Since I came across inline views in my reading, I tried the approach recommended by g feng, although I am eager to try the other approaches too.
    I ended up using an inner join simply to get more descriptive info. on the column that was being counted. With Y representing this second table, Y.B being the column containing the descriptive info., and A being the common key between X and Y, here is the simple code I came up with.
    SELECT Y.B, V.*
    FROM Y,
    SELECT A AV, COUNT (*)
    FROM X
    GROUP BY A
    ) V
    WHERE V.AV = Y.A
    Does this seem correct... anything I need to watch out for?
    Thanks again to everyone for your help!!
    Holly

  • Using ORDER BY for column that's not in SELECT statement of select list?

    Hi all.
    I have a select list on an APEX page at apex.oracle.com, and I would like to order this by the value of column UnitOrder.
    The SQL is as follows:
    SELECT DISTINCT foodunit.name AS display_value, foodunit.foodunitid AS return_value
    FROM foodunit, food
    WHERE foodunit.foodid = :P18_FOODID
    ORDER BY foodunit.unitorder ASC;Off course, this code won't work. And since it's a select list, I can't just add foodunit.unitorder to the SELECT statement. Also, I can't get rid of the DISTINCT, because then for some reason it tends to display an infinite amount of the same row...
    The point of ordering it by UnitOrder is that all units who begin with gram, ml, mg, kg,... etc, will be shown on top of the select list. All other food units will be shown on the second place and so on.
    The column UnitOrder holds either 1 or 2 as a value. 1 is the value for all rows that should be displayed at the top of the select list, 2 is the value for all the rest.
    So, what I want is that all rows in which the UnitOrder is 1, get displayed on top of the select list. Usually only 2 list items get shown in the select list at a time, depening on which food item a user has selected. The select list then refines to certain rows that match the foodid etc etc..
    If anyone has an idea, I'd be very happy to hear about it.

    Thanks! I didn't think about using a join. Code works now, and is as follows:
    SELECT foodunit.name AS display_value, foodunit.foodunitid AS return_value
    FROM foodunit
    INNER JOIN food
    ON food.foodid = foodunit.foodid 
    WHERE foodunit.foodid = :P18_FOODID
    ORDER BY foodunit.unitorder ASC;

  • OBIEE not selecting columns from all LTS of a Conforming Degener@teDimen$ion

    Hello everyone
        I have a Degener@teDimen$ion Dimension A it has 4 LTS ( Fact1, Fact1A ,Fact2 and FACT2A).--> FACTS from
    Physical Layer.. FACTS in BMM are FACT_ONe and FACT_TWO.
    columns in Degener@teDimen$ion Dimension A
    col1 --> mapped to all 4 LTS(logical source). It is the key column.
    col2 --> mapped to all 4 LTS(logical source)
    col3 --> mapped to all 4 LTS(logical source)
    The content Tab of the LTS for this Dimension are mapped to Detail of
    Dimension Hierarchy name is DDimension A
    Dimension Hierarchy name is DDimension A, Levels in it are
    Total --> This has all the fact columns from FACT1 and FACT2. Basically dragged dropped from facts to
    this level.
    & Detail ---> It has col1,col2 and col3 and Degener@teDimen$ion Dimension A.
    FACT_ONE --> Fact1, Fact1A are LTS for this fact 
    FACT_TWO --> Fact2 and FACT2A are LTS for this fact.
    When i am doing a analysis with
    Year, Degener@teDimen$ion_Dimension A_COL2 , FACT_ONE.measure1, FACT_TWO.measure1
    It is basically showing the dimension value of FACT_TWO.measure1 only...
    even the select statement is not having column from FACT_ONE...
    Like
    select x,y, col2 from fact_two full outer join select x,y from fact_one...> I just provided this
    syntax just for an idea.. the this fact_one is not having that column in the select..
    I referred this link
    "http://www.rittmanmead.com/2010/01/oracle-bi-ee-10-1-3-4-1-modeling-degenerate-dimensions-fact-attributes/"
    and others but i am not able to find the reason why it is not issuing a select...
    Just to add more in the Total level of the hierarchy, if i added FACT_TWO only removed FACT_ONE measures..
    it is showing only fact_one value (this time the FACT_ONE SELECT is having col2 but not FACT_TWO)...
    the behaviuor is vice versa as well...

    I resolved this. The Issue is, when using Degener@teDimen$ion ( this is !nner joned to FACT tables in BMM) and if any of the dimensions {other than the Degener@teDimen$ion (Let us say Dim X) } have an ()uter join to any of the fact tables, and you were doing your analysis using Degener@teDimen$ion,  Dim X, Measure value you will face the following issues.
    when filtering the analysis on the ()uter join dimension ( Dim X), the IN filter will not work. Reason is that the filter is getting applied to both the Dimension and FACT tables and the values that exist in Dimension Dim X but not in FACT table wont show up.
         The above issue can be fixed by changing the join between the fact and Degener@teDimen$ion from inner to outer. I think this is a bug.. because  it is supposed to filter the fact  table after the entire outer joined result is obtained but not filter the fact table for the Dim X values and do a outer join. I think the BI should be intelligent enough.
         In order to solve the filtering issue what i did was mentioned in my Initial post. I think if we have the measures at the Totals level of dimension, it is picking the Degener@teDimen$ion,from the table that has less number of rows or the query from one of the two facts that gets submitted to database.. I couldn't find the relevant information in the oracle document though . . . .

  • SELECT STATEMENT FROM THIS TABLES

    HI FRIENDS,
    PLE HELP ME REGARDING THIS.
    data from 3 tables
    TABLES: CUST_CONT,CONT_CAT_FOLD,CONT_FOLD_***
    cust_cont_pk (IS COMMON FIELD IN TABLE I AND 3)
    cont_cat_fold_pk( IS COMMON FIELD IN TABLE 2 AND 3)
    HOW CAN I WRITE SELECT STATEMENT
    Thanking u
    suneel.

    Hi
    Join the two tables
    CUST_CONT  and CONT_FOLD_*** with cust_cont_pk  field and
    CONT_CAT_FOLD and CONT_FOLD_*** with cont_cat_fold_pk field
    see the doc
    Joins are used to fetch data fast from Database tables:
    Tables are joined with the proper key fields to fetch the data properly.
    If there are no proper key fields between tables don't use Joins;
    Important thing is that don't USE JOINS FOR CLUSTER tableslike BSEG and KONV.
    Only use for Transparenmt tables.
    You can also use joins for the database VIews to fetch the data.
    JOINS
    ... FROM tabref1 [INNER] JOIN tabref2 ON cond
    Effect
    The data is to be selected from transparent database tables and/or views determined by tabref1 and tabref2. tabref1 and tabref2 each have the same form as in variant 1 or are themselves Join expressions. The keyword INNER does not have to be specified. The database tables or views determined by tabref1 and tabref2 must be recognized by the ABAP Dictionary.
    In a relational data structure, it is quite normal for data that belongs together to be split up across several tables to help the process of standardization (see relational databases). To regroup this information into a database query, you can link tables using the join command. This formulates conditions for the columns in the tables involved. The inner join contains all combinations of lines from the database table determined by tabref1 with lines from the table determined by tabref2, whose values together meet the logical condition (join condition) specified using ON>cond.
    Inner join between table 1 and table 2, where column D in both tables in the join condition is set the same:
    Table 1 Table 2
    A
    B
    C
    D
    D
    E
    F
    G
    H
    a1
    b1
    c1
    1
    1
    e1
    f1
    g1
    h1
    a2
    b2
    c2
    1
    3
    e2
    f2
    g2
    h2
    a3
    b3
    c3
    2
    4
    e3
    f3
    g3
    h3
    a4
    b4
    c4
    3
    |--|||--|
    Inner Join
    A
    B
    C
    D
    D
    E
    F
    G
    H
    a1
    b1
    c1
    1
    1
    e1
    f1
    g1
    h1
    a2
    b2
    c2
    1
    1
    e1
    f1
    g1
    h1
    a4
    b4
    c4
    3
    3
    e2
    f2
    g2
    h2
    |--||||||||--|
    Example
    Output a list of all flights from Frankfurt to New York between September 10th and 20th, 2001 that are not sold out:
    DATA: DATE LIKE SFLIGHT-FLDATE,
    CARRID LIKE SFLIGHT-CARRID,
    CONNID LIKE SFLIGHT-CONNID.
    SELECT FCARRID FCONNID F~FLDATE
    INTO (CARRID, CONNID, DATE)
    FROM SFLIGHT AS F INNER JOIN SPFLI AS P
    ON FCARRID = PCARRID AND
    FCONNID = PCONNID
    WHERE P~CITYFROM = 'FRANKFURT'
    AND P~CITYTO = 'NEW YORK'
    AND F~FLDATE BETWEEN '20010910' AND '20010920'
    AND FSEATSOCC < FSEATSMAX.
    WRITE: / DATE, CARRID, CONNID.
    ENDSELECT.
    If there are columns with the same name in both tables, you must distinguish between them by prefixing the field descriptor with the table name or a table alias.
    Note
    In order to determine the result of a SELECT command where the FROM clause contains a join, the database system first creates a temporary table containing the lines that meet the ON condition. The WHERE condition is then applied to the temporary table. It does not matter in an inner join whether the condition is in the ON or WHEREclause. The following example returns the same solution as the previous one.
    Example
    Output of a list of all flights from Frankfurt to New York between September 10th and 20th, 2001 that are not sold out:
    DATA: DATE LIKE SFLIGHT-FLDATE,
    CARRID LIKE SFLIGHT-CARRID,
    CONNID LIKE SFLIGHT-CONNID.
    SELECT FCARRID FCONNID F~FLDATE
    INTO (CARRID, CONNID, DATE)
    FROM SFLIGHT AS F INNER JOIN SPFLI AS P
    ON FCARRID = PCARRID
    WHERE FCONNID = PCONNID
    AND P~CITYFROM = 'FRANKFURT'
    AND P~CITYTO = 'NEW YORK'
    AND F~FLDATE BETWEEN '20010910' AND '20010920'
    AND FSEATSOCC < FSEATSMAX.
    WRITE: / DATE, CARRID, CONNID.
    ENDSELECT.
    Note
    Since not all of the database systems supported by SAP use the standard syntax for ON conditions, the syntax has been restricted. It only allows those joins that produce the same results on all of the supported database systems:
    Only a table or view may appear to the right of the JOIN operator, not another join expression.
    Only AND is possible in the ON condition as a logical operator.
    Each comparison in the ON condition must contain a field from the right-hand table.
    If an outer join occurs in the FROM clause, all the ON conditions must contain at least one "real" JOIN condition (a condition that contains a field from tabref1 amd a field from tabref2.
    Note
    In some cases, '*' may be specified in the SELECT clause, and an internal table or work area is entered into the INTO clause (instead of a list of fields). If so, the fields are written to the target area from left to right in the order in which the tables appear in the FROM clause, according to the structure of each table work area. There can then be gaps between table work areas if you use an Alignment Request. For this reason, you should define the target work area with reference to the types of the database tables, not simply by counting the total number of fields. For an example, see below:
    Variant 3
    ... FROM tabref1 LEFT [OUTER] JOIN tabref2 ON cond
    Effect
    Selects the data from the transparent database tables and/or views specified in tabref1 and tabref2. tabref1 und tabref2 both have either the same form as in variant 1 or are themselves join expressions. The keyword OUTER can be omitted. The database tables or views specified in tabref1 and tabref2 must be recognized by the ABAP-Dictionary.
    In order to determine the result of a SELECT command where the FROM clause contains a left outer join, the database system creates a temporary table containing the lines that meet the ON condition. The remaining fields from the left-hand table (tabref1) are then added to this table, and their corresponding fields from the right-hand table are filled with ZERO values. The system then applies the WHERE condition to the table.
    Left outer join between table 1 and table 2 where column D in both tables set the join condition:
    Table 1 Table 2
    A
    B
    C
    D
    D
    E
    F
    G
    H
    a1
    b1
    c1
    1
    1
    e1
    f1
    g1
    h1
    a2
    b2
    c2
    1
    3
    e2
    f2
    g2
    h2
    a3
    b3
    c3
    2
    4
    e3
    f3
    g3
    h3
    a4
    b4
    c4
    3
    |--|||--|
    Left Outer Join
    A
    B
    C
    D
    D
    E
    F
    G
    H
    a1
    b1
    c1
    1
    1
    e1
    f1
    g1
    h1
    a2
    b2
    c2
    1
    1
    e1
    f1
    g1
    h1
    a3
    b3
    c3
    2
    NULL
    NULL
    NULL
    NULL
    NULL
    a4
    b4
    c4
    3
    3
    e2
    f2
    g2
    h2
    |--||||||||--|
    Example
    Output a list of all custimers with their bookings for October 15th, 2001:
    DATA: CUSTOMER TYPE SCUSTOM,
    BOOKING TYPE SBOOK.
    SELECT SCUSTOMNAME SCUSTOMPOSTCODE SCUSTOM~CITY
    SBOOKFLDATE SBOOKCARRID SBOOKCONNID SBOOKBOOKID
    INTO (CUSTOMER-NAME, CUSTOMER-POSTCODE, CUSTOMER-CITY,
    BOOKING-FLDATE, BOOKING-CARRID, BOOKING-CONNID,
    BOOKING-BOOKID)
    FROM SCUSTOM LEFT OUTER JOIN SBOOK
    ON SCUSTOMID = SBOOKCUSTOMID AND
    SBOOK~FLDATE = '20011015'
    ORDER BY SCUSTOMNAME SBOOKFLDATE.
    WRITE: / CUSTOMER-NAME, CUSTOMER-POSTCODE, CUSTOMER-CITY,
    BOOKING-FLDATE, BOOKING-CARRID, BOOKING-CONNID,
    BOOKING-BOOKID.
    ENDSELECT.
    If there are columns with the same name in both tables, you must distinguish between them by prefixing the field descriptor with the table name or using an alias.
    Note
    For the resulting set of a SELECT command with a left outer join in the FROM clause, it is generally of crucial importance whether a logical condition is in the ON or WHERE condition. Since not all of the database systems supported by SAP themselves support the standard syntax and semantics of the left outer join, the syntax has been restricted to those cases that return the same solution in all database systems:
    Only a table or view may come after the JOIN operator, not another join statement.
    The only logical operator allowed in the ON condition is AND.
    Each comparison in the ON condition must contain a field from the right-hand table.
    Comparisons in the WHERE condition must not contain a field from the right-hand table.
    The ON condition must contain at least one "real" JOIN condition (a condition in which a field from tabref1 as well as from tabref2 occurs).
    Note
    In some cases, '*' may be specivied as the field list in the SELECT clause, and an internal table or work area is entered in the INTO clause (instead of a list of fields). If so, the fields are written to the target area from left to right in the order in which the tables appear in the llen in der FROM clause, according to the structure of each table work area. There can be gaps between the table work areas if you use an Alignment Request. For this reason, you should define the target work area with reference to the types of the database tables, as in the following example (not simply by counting the total number of fields).
    Example
    Example of a JOIN with more than two tables: Select all flights from Frankfurt to New York between September 10th and 20th, 2001 where there are available places, and display the name of the airline.
    DATA: BEGIN OF WA,
    FLIGHT TYPE SFLIGHT,
    PFLI TYPE SPFLI,
    CARR TYPE SCARR,
    END OF WA.
    SELECT * INTO WA
    FROM ( SFLIGHT AS F INNER JOIN SPFLI AS P
    ON FCARRID = PCARRID AND
    FCONNID = PCONNID )
    INNER JOIN SCARR AS C
    ON FCARRID = CCARRID
    WHERE P~CITYFROM = 'FRANKFURT'
    AND P~CITYTO = 'NEW YORK'
    AND F~FLDATE BETWEEN '20010910' AND '20010920'
    AND FSEATSOCC < FSEATSMAX.
    WRITE: / WA-CARR-CARRNAME, WA-FLIGHT-FLDATE, WA-FLIGHT-CARRID,
    WA-FLIGHT-CONNID.
    ENDSELECT.
    reward points if useful
    regards
    Anji

  • Values from a Multi-Select in the where clause of a Select statement

    I have a web page that solicits query parameters from the user.
    The selections that the user makes will populate the WHERE clause of a Select statement.
    One of the controls on the page is a multi-select control.
    When this page posts, I would like to execute a Select statement wherein the selected values from this control appear in the .. Column IN ( <list here> ) portion of the WHERE clause.
    This is an extremely common scenario, but I cannot seem to locate a how-to or message thread that addresses this specific case.
    I have an idea that it may involve dynamic SQL or Execute Immediate, but cannot seem to pin down the answer.
    Any help would be greatly appreciated!

    anonymous - As illustrated here: Re: Search on a typed in list of values
    Scott

  • Return multiple values from a function to a SELECT statement

    I hope I've provided enough information here. If not, just let me know what I'm missing.
    I am creating a view that will combine information from a few tables. Most of it is fairly straightforward, but there are a couple of columns in the view that I need to get by running a function within a package. Even this is fairly straightforward (I have a function named action_date in a package called rp, for instance, which I can use to return the date I need via SELECT rp.action_date(sequence_number).
    Here's the issue: I actually need to return several bits of information from the same record (not just action_date, but also action_office, action_value, etc.) - a join of the tables won't work here as I'll explain below. I can, of course, run a separate function for each statement but that is obviously inefficient. Within the confines of the view select statement however, I'm not sure how to return each of the values I need.
    For instance, right now, I have:
    Table1:
    sequence_number NUMBER(10),
    name VARCHAR(30),
    Table2:
    Table1_seq NUMBER(10),
    action_seq NUMBER(10),
    action_date DATE,
    action_office VARCHAR(3),
    action_value VARCHAR(60),
    I can't simply join Table1 and Table2 because I have to do some processing in order to determine which of the matching returned rows I actually need to select. So the package opens a cursor and processes each row until it finds the one that I need.
    The following works but is inefficient since all of the calls to the package will return columns from the same record. I just don't know how to return all the values I need into the SELECT statement.
    CREATE VIEW all_this_stuff AS
    SELECT sequence_number, name,
    rp.action_date(sequence_number) action_date,
    rp.action_office(sequence_number) action_office,
    rp.action_value(sequence_number) action_value
    FROM table1
    Is there a way to return multiple values into my SELECT statement or am I going about this all wrong?
    Any suggestions?
    Thanks so much!

    Hi,
    What you want is a Top-N Query , which you can do using the analytic ROW_NUMBER function in a sub-query, like this:
    WITH     got_rnum     AS
         SELECT     action_seq, action_dt, action_office, action_type, action_value
         ,     ROW_NUMBER () OVER ( ORDER BY  action_date
                                   ,            action_seq
                             ,            action_serial
                           ) AS rnum
         FROM     table2
         WHERE     action_code     = 'AB'
         AND     action_office     LIKE 'E'     -- Is this right?
    SELECT     action_seq, action_dt, action_office, action_type, action_value
    FROM     got_rnum
    WHERE     rnum     = 1
    ;As written, this will return (at most) one row.
    I suspect you'll really want to get one row for each group , where a group is defined by some value in a table to which you're joining.
    In that case, add a PARTITION BY clause to the ROW_NUMBER function.
    If you'd post a little sample data (CREATE TABLE and INSERT statements), I could show you exactly how.
    Since I don't have your tables, I'll show you using tables in the scott schema.
    Here's a view that has data from the scott.dept table and also from scott.emp, but only for the most senior employee in each department (that is, the employee with the earliest hiredate). If there happens to be a tie for the earliest hiredate, then the contender with the lowest empno is chosen.
    CREATE OR REPLACE VIEW     senior_emp
    AS
    WITH     got_rnum     AS
         SELECT     d.deptno
         ,     d.dname
         ,     e.empno
         ,     e.ename
         ,     e.hiredate
         ,     ROW_NUMBER () OVER ( PARTITION BY  d.deptno
                                   ORDER BY          e.hiredate
                             ,                e.empno
                           ) AS rnum
         FROM     scott.dept     d
         JOIN     scott.emp     e     ON     d.deptno     = e.deptno
    SELECT     deptno
    ,     dname
    ,     empno
    ,     ename
    ,     hiredate
    FROM     got_rnum
    WHERE     rnum     = 1
    SELECT     *
    FROM     senior_emp
    ;Output:
    .    DEPTNO DNAME               EMPNO ENAME      HIREDATE
            10 ACCOUNTING           7782 CLARK      09-JUN-81
            20 RESEARCH             7369 SMITH      17-DEC-80
            30 SALES                7499 ALLEN      20-FEB-81 
    By the way, one of the conditions in the query you posted was
    action_office     LIKE 'E'which is equivalent to
    action_office     = 'E'(LIKE is always equivalent to = if the string after LIKE doesn't contain any wildcards.)
    Did you mean to say that, or did you mean something like this:
    action_office     LIKE 'E%'instead?

  • MSSQLServer4 - Accessing columns from a select with the same name

    The following describes a problem I'm encountering using the MSSQLServer4 driver...I have the following 2 tables (greatly simplified):
    Create Table BOOK( BookId int, Name varchar(50), AuthorId int )
    Create Table AUTHOR( AuthorId int, Name varchar(30) )
    and my select is
    Select BOOK.*, AUTHOR.*
    From BOOK Inner Join AUTHOR On BOOK.AUTHORID = AUTHOR.AUTHORID
    As you can see, the ResultSet from this select will have 2 identically named columns called "Name". I realize I could use an alias to differentiate the column names, but then I must list out every column in each table (quite ugly). I had EXPECTED to be able to do a resultSet.getString( "Author.Name" ), but that doesn't appear to work either. Next, I thought I could use the ResultSetMetaData.getTable()/ResultSetMetaData.getColumnName() to determine the ordinal value, but getTable() always returns "". Is there anyway to distinguish these two columns without using an alias?
    Any help is greatly appreciated.
    Regards...Marc

    Marc wrote:
    The following describes a problem I'm encountering using the MSSQLServer4 driver...I have the following 2 tables (greatly simplified):
    Create Table BOOK( BookId int, Name varchar(50), AuthorId int )
    Create Table AUTHOR( AuthorId int, Name varchar(30) )
    and my select is
    Select BOOK.*, AUTHOR.*
    From BOOK Inner Join AUTHOR On BOOK.AUTHORID = AUTHOR.AUTHORID
    As you can see, the ResultSet from this select will have 2 identically named columns called "Name". I realize I could use an alias to differentiate the column names, but then I must list out every column in each table (quite ugly). I had EXPECTED to be able to do a resultSet.getString( "Author.Name" ), but that doesn't appear to work either. Next, I thought I could use the ResultSetMetaData.getTable()/ResultSetMetaData.getColumnName() to determine the ordinal value, but getTable() always returns "". Is there anyway to distinguish these two columns without using an alias?
    Any help is greatly appreciated.
    Regards...MarcHi. getTableName() will never work because the DBMS doesn't send the necessary metadata with the result
    set that the driver would need to implement that call. If you get 'Name' for multiple column names, JDBC specifies
    that getXXX("Name") will always return the first such named column. The only non-alias way is to know
    the columns you're going to get in order, and just do getXXX(1), getXXX(2) etc.
    Joe

  • How to use column name as variable in select statement

    hi,
    i want to make a sql query where in select statement using variable as a column name. but its not working plz guide me how can i do this.
    select :m1 from table1;
    regards

    Hi,
    Is this what you want..
    SQL> select &m1 from dept;
    Enter value for m1: deptno
    old   1: select &m1 from dept
    new   1: select deptno from dept
        DEPTNO
            10
            20
            30
            40
    SQL> select &m1 from dept;
    Enter value for m1: dname
    old   1: select &m1 from dept
    new   1: select dname from dept
    DNAME
    ACCOUNTING
    RESEARCH
    SALES
    OPERATIONS
    SQL> select &&m1 from dept;
    Enter value for m1: loc
    old   1: select &&m1 from dept
    new   1: select loc from dept
    LOC
    NEW YORK
    DALLAS
    CHICAGO
    BOSTON
    SQL> select &&m1 from dept;
    old   1: select &&m1 from dept
    new   1: select loc from dept
    LOC
    NEW YORK
    DALLAS
    CHICAGO
    BOSTONIf you use single '&' then each time you fire the query, It will ask for the new value..
    But if you will use double '&&' the value of m1 will be persistent across the session..
    Twinkle

  • In Oracle SQL, cannot use column in select statement and order by

    Hi,
    Is there a work around for this.
    Thanks in advance
    Pablo.

    Hi,
    943981 wrote:
    Hi All,
    This is the error I get:
    ORA-00960: ambiguous column naming in select list
    00960. 00000 - "ambiguous column naming in select list"
    *Cause:    A column name in the order-by list matches more than one select
    list columns.
    *Action:   Remove duplicate column naming in select list.
    Error at Line: 6 Column: 17That error message looks pretty clear to me. What don't you understand?
    Either
    (a) use aliases, so each column has a unique name, or
    (b) remove duplicate columns from the SELECT clause.
    Post your query. It's hard to say exactly what you're doing wrong when we don't know exactly what you're doing.
    For best results, post a complete test script (including CREATE TABLE and INSERT statements, if necessary) that people can to re-create the problem and test their ideas.
    See the forum FAQ {message:id=9360002}

  • Select LONG column from Remote table

    Hi to all.
    I have the following problem: I can't select a LONG column from remote database, when there are Join operation in the query. Example:
    SELECT long_column FROM remote_table@DB
    -> that's OK, but:
    SELECT long_column FROM remote_table@DB INNER JOIN remote_table2@DB ON ...
    -> returns: "ORA-00997: Illegal use of LONG datatype"
    I cannot even perform (because there a LONG column in the joined table):
    SELECT nonlong_column FROM remote_table@DB INNER JOIN remote_table2@DB ON ...
    That's very strange to me because:
    SELECT long_column FROM local_table INNER JOIN local_table2 ON ...
    -> is OK!
    Can someone help me to SELECT a long column from remote in SELECT query with JOIN clause!
    Thanks a lot!

    Hi
    "Distributed queries are currently subject to the restriction that all tables locked by a FOR UPDATE clause and all tables with LONG columns selected by the query must be located on the same database. " by otn docs.
    I have no idea.
    Ott Karesz
    http://www.trendo-kft.hu

  • Using column number inplace of column name in SQL Select statement

    Is there a way to run sql select statements with column numbers in
    place of column names?
    Current SQL
    select AddressId,Name,City from AddressIs this possible
    select 1,2,5 from AddressThanks in Advance

    user10962462 wrote:
    well, ok, it's not possible with SQL, but how about PL/SQL?As mentioned, using DBMS_SQL you can only really use positional notation... and you can also use those positions to get the other information such as what the column is called, what it's datatype is etc.
    CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2) IS
      v_v_val     VARCHAR2(4000);
      v_n_val     NUMBER;
      v_d_val     DATE;
      v_ret       NUMBER;
      c           NUMBER;
      d           NUMBER;
      col_cnt     INTEGER;
      f           BOOLEAN;
      rec_tab     DBMS_SQL.DESC_TAB;
      col_num     NUMBER;
      v_rowcount  NUMBER := 0;
    BEGIN
      -- create a cursor
      c := DBMS_SQL.OPEN_CURSOR;
      -- parse the SQL statement into the cursor
      DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
      -- execute the cursor
      d := DBMS_SQL.EXECUTE(c);
      -- Describe the columns returned by the SQL statement
      DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
      -- Bind local return variables to the various columns based on their types
      FOR j in 1..col_cnt
      LOOP
        CASE rec_tab(j).col_type
          WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); -- Varchar2
          WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);      -- Number
          WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);     -- Date
        ELSE
          DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);  -- Any other type return as varchar2
        END CASE;
      END LOOP;
      -- Display what columns are being returned...
      DBMS_OUTPUT.PUT_LINE('-- Columns --');
      FOR j in 1..col_cnt
      LOOP
        DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' - '||case rec_tab(j).col_type when 1 then 'VARCHAR2'
                                                                                  when 2 then 'NUMBER'
                                                                                  when 12 then 'DATE'
                                                         else 'Other' end);
      END LOOP;
      DBMS_OUTPUT.PUT_LINE('-------------');
      -- This part outputs the DATA
      LOOP
        -- Fetch a row of data through the cursor
        v_ret := DBMS_SQL.FETCH_ROWS(c);
        -- Exit when no more rows
        EXIT WHEN v_ret = 0;
        v_rowcount := v_rowcount + 1;
        DBMS_OUTPUT.PUT_LINE('Row: '||v_rowcount);
        DBMS_OUTPUT.PUT_LINE('--------------');
        -- Fetch the value of each column from the row
        FOR j in 1..col_cnt
        LOOP
          -- Fetch each column into the correct data type based on the description of the column
          CASE rec_tab(j).col_type
            WHEN 1  THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                         DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
            WHEN 2  THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                         DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_n_val);
            WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                         DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'));
          ELSE
            DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
            DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
          END CASE;
        END LOOP;
        DBMS_OUTPUT.PUT_LINE('--------------');
      END LOOP;
      -- Close the cursor now we have finished with it
      DBMS_SQL.CLOSE_CURSOR(c);
    END;
    SQL> exec run_query('select empno, ename, deptno, sal from emp where deptno = 10');
    -- Columns --
    EMPNO - NUMBER
    ENAME - VARCHAR2
    DEPTNO - NUMBER
    SAL - NUMBER
    Row: 1
    EMPNO : 7782
    ENAME : CLARK
    DEPTNO : 10
    SAL : 2450
    Row: 2
    EMPNO : 7839
    ENAME : KING
    DEPTNO : 10
    SAL : 5000
    Row: 3
    EMPNO : 7934
    ENAME : MILLER
    DEPTNO : 10
    SAL : 1300
    PL/SQL procedure successfully completed.
    SQL> exec run_query('select * from emp where deptno = 10');
    -- Columns --
    EMPNO - NUMBER
    ENAME - VARCHAR2
    JOB - VARCHAR2
    MGR - NUMBER
    HIREDATE - DATE
    SAL - NUMBER
    COMM - NUMBER
    DEPTNO - NUMBER
    Row: 1
    EMPNO : 7782
    ENAME : CLARK
    JOB : MANAGER
    MGR : 7839
    HIREDATE : 09/06/1981 00:00:00
    SAL : 2450
    COMM :
    DEPTNO : 10
    Row: 2
    EMPNO : 7839
    ENAME : KING
    JOB : PRESIDENT
    MGR :
    HIREDATE : 17/11/1981 00:00:00
    SAL : 5000
    COMM :
    DEPTNO : 10
    Row: 3
    EMPNO : 7934
    ENAME : MILLER
    JOB : CLERK
    MGR : 7782
    HIREDATE : 23/01/1982 00:00:00
    SAL : 1300
    COMM :
    DEPTNO : 10
    PL/SQL procedure successfully completed.
    SQL> exec run_query('select * from dept where deptno = 10');
    -- Columns --
    DEPTNO - NUMBER
    DNAME - VARCHAR2
    LOC - VARCHAR2
    Row: 1
    DEPTNO : 10
    DNAME : ACCOUNTING
    LOC : NEW YORK
    PL/SQL procedure successfully completed.
    SQL>

Maybe you are looking for

  • Creation of number range in NRIV table

    Dear All, User is asking to maintain the number range in the NRIV table with object name RV_BELEG. As shown below:- Object name  Subobj.val    No    Year    From no.        To number    No. status     Ext RV_BELEG                           D1        

  • How do I make use of the Composite Video input jack on my HP pavilion Elite m9150f computer?

    I have a Pavilion Elite m9150f computer that has front panel jacks labeled "Composite Video Input,and Audio left and Audio right input" They are all RCA type.None of the PDF type manual files mention these jacks.I would like to make use of them to in

  • Tablespace 88% full will impact performance?

    Hi, I have a tablespace with 10 datafile in a disk.The tablespaces id 88% full with 9 datafiles being 99% and 1 left with 10% .will this impact the performance. or is it ok

  • Workitem ID wise to get the Object value

    Hi All, is it possible to get the object value form Workitem id wise. for example workitem id '446085' based on that workitem id i want to retrieve the object value. Please clarify., Thanks & Regards K.Gunasekar.

  • DW8 Site manager very slow

    All of a sudden my DW8 Site Manager takes ages to let me edit a site. It does eventually open the site, but has me wait for several minutes. The problems affects all sites. I have renamed my configuration folder and a new one was duly created but the