Make 1 row turn into X rows, based on value X in column?

Hello everyone, got a question for you! I've got a table as follows:
ITEM_NUM,IN_STOCK
1001A,2
1001B,1
1001C,2
1001D,3
I'd like to get the following output:
1 1001A
2 1001A
3 1001B
4 1001C
5 1001C
6 1001D
7 1001D
8 1001D
So each row gets repeated for as many times as it has for the in_stock value. And down the left side, we get rownum.
I can do this with PL/SQL code (a cursor to get both columns, and for each row, run a loop to place these into a collection). But if there's a way just to skip the loop and write a query, I'd rather do this!
Thanks!
-Thomas H

Well you can pretty much use any row source here but I favour pipelined function for overall simplicity / clarity and performance.
Personal Oracle Database 10g Release 10.1.0.2.0 - Production
With the Partitioning, OLAP and Data Mining options
SQL> CREATE TABLE t (item_num VARCHAR2 (5), in_stock NUMBER);
Table created.
SQL> INSERT INTO t VALUES ('1001A',2);
1 row created.
SQL> INSERT INTO t VALUES ('1001B',1);
1 row created.
SQL> INSERT INTO t VALUES ('1001C',2);
1 row created.
SQL> INSERT INTO t VALUES ('1001D',3);
1 row created.
SQL> CREATE OR REPLACE FUNCTION many (
  2    p_rows IN NUMBER)
  3    RETURN number_table PIPELINED
  4  IS
  5  BEGIN
  6    FOR l_row IN 1..p_rows LOOP
  7      PIPE ROW (l_row);
  8    END LOOP;
  9    RETURN;
10  END;
11  /
Function created.
SQL> SELECT ROWNUM, item_num
  2  FROM   t, TABLE (many (in_stock));
    ROWNUM ITEM_
         1 1001A
         2 1001A
         3 1001B
         4 1001C
         5 1001C
         6 1001D
         7 1001D
         8 1001D
8 rows selected.
SQL>

Similar Messages

  • Dynamically display title based on value selected in column selector

    Hi All,
    Can it be possible to show the report title dynamically based on value selected in column selector . suppose i have two column status and region . When i will select status in the column selector the title of the report will show " Status Summary" when i will select region then the title will change to "Region Summary". Please help me...

    Hi,
    create dashboard prompt with column selector functionality like following way
    write the following query in your dashboard prompt sql results
    select region name from subject area name
    Union all
    select sub_region name from subject area name
    like this and put one presentation variable for this dashboard prompt like var1
    in your report write formula in your column like this *case when @{var1)='region column' then 'Region Summary' else ' ' end*
    and refer this column in narrative view like @1 then narrative act like a title view.
    Hope this helps you
    Regards
    Naresh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Making whole row coloured red based on value in one column in BI Answers.

    Hi
    Would anyone know how to make a whole row red (eg) based on the value from one column within the row in
    a BI Answers report in either a pivot table or a table view. I know it should be a case of setting up the
    conditional formatting in the Conditional Tab on the Properties of the column, but all the columns apart from the
    one with the value being determined ignore the value in another column.
    Thanks,
    - Pete
    Edited by: user1636556 on 09-Dec-2011 07:58

    Hi
    Would anyone know how to make a whole row red (eg) based on the value from one column within the row in
    a BI Answers report in either a pivot table or a table view. I know it should be a case of setting up the
    conditional formatting in the Conditional Tab on the Properties of the column, but all the columns apart from the
    one with the value being determined ignore the value in another column.
    Thanks,
    - Pete
    Edited by: user1636556 on 09-Dec-2011 07:58

  • How to break one row records into 3 row records

    I have two tables which consists of date records,
    table1
    first_date second_date
    01-feb-10 01-mar-10
    tabl2
    new_date old_date
    01-jan-10 01-aug-10
    if first table dates falls between new_date and old_dates, i need to showit as three row records instead of1 row in table2

    Hi,
    1001383 wrote:
    I have two tables which consists of date records,
    table1
    first_date second_date
    01-feb-10 01-mar-10
    tabl2
    new_date old_date
    01-jan-10 01-aug-10
    if first table dates falls between new_date and old_dates, i need to showit as three row records instead of1 row in table2Do both first_date and second_date have to fall between old_date and new_date, or is it enough if either one does?
    What do you want to see on those 3 rows?
    Depending on your data and your requirements, here's one way:
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL     <= 3
    SELECT  t2.*
    FROM          table2     t2
    CROSS JOIN     cntr
    WHERE   EXISTS (
    '              SELECT  1
                  FROM    table1     t1
                  WHERE   t1.first_date     BETWEEN t2.old_date AND t2.new_date
                  OR         t1.second_date     BETWEEN t2.old_date AND t2.new_date
    ;I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements) for both tables, and the results you want from that data.
    Include examples of any special situations you need to handle, such as the same row in table2 matching several rows in table1.
    See the forum FAQ {message:id=9360002}

  • Insert value into a column based on value of another column

    Hi,
    I am trying to insert a value into a record based on a column in
    the record, using a trigger. The complication arises because
    the new value is selected from the same table. For example:
    SELECT COL1, COL2, COL3, COL4 from TABLE1
    I want to set COL2 and COL3 based on the value of COL4. And to
    get the value of COL2 and COL3, I will go back to TABLE1 and set
    the condition to TABLE1.COL1 = :NEW.COL4
    I cannot seem to execute the trigger as I get the message "ORA-
    04091: table SYSTEM.TABLE1 is mutating, trigger/function may not
    see it" everytime.
    Is this the correct way to achieve what I wanted? Or is there
    another way?
    Appreciate your feedback. Thank you in advance.

    Hi,
    I am trying to insert a value into a record based on a column in
    the record, using a trigger. The complication arises because
    the new value is selected from the same table. For example:
    SELECT COL1, COL2, COL3, COL4 from TABLE1
    I want to set COL2 and COL3 based on the value of COL4. And to
    get the value of COL2 and COL3, I will go back to TABLE1 and set
    the condition to TABLE1.COL1 = :NEW.COL4
    I cannot seem to execute the trigger as I get the message "ORA-
    04091: table SYSTEM.TABLE1 is mutating, trigger/function may not
    see it" everytime.
    Is this the correct way to achieve what I wanted? Or is there
    another way?
    Appreciate your feedback. Thank you in advance. I'm not sure what you mean when you insert a value into a
    record, but if you are setting a value in a column of the same
    record using a trigger, then it's easy.
    :new.COL2 := ....:new.COL4...
    :new.COL3 := ....:new.COL4...
    The trigger must be 'INSERT or UPDATE' and 'FOR EACH RECORD'.
    If you are setting a different record in the same table, the
    solution is much more difficult.

  • How to make dataload fast into a table having CONTEXT index on CLOB column?

    Hi all,
    I have a table with the follwing structure :
       CREATE TABLE file_table (
           file_id    NUMBER(10) PRIMARY KEY,
           file_name  VARCHAR2(3000),
           file_data CLOB);I am loading around 50,000 files into the table using SQL*LOADER.
    LOAD DATA
    INFILE * BADFILE  'd:\mydata.bad' DISCARDFILE 'd:\mydata.dis'
    INTO TABLE file_table
    APPEND
    FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'
    file_name  CHAR(1000),
    file_data  LOBFILE (file_name) TERMINATED BY EOF
    BEGINDATA
    D:\TEXT\9701.1\00\00\01.txt
    D:\TEXT\9701.1\01\01\03.txt
    D:\TEXT\9701.2\02\02\04.txt
    D:\TEXT\9701.3\03\03\05.txt
    ..after this I am creating Text index :
    CREATE INDEX file_table_idx ON file_table (file_data)
    INDEXTYPE IS CTXSYS.CONTEXT online 
    PARAMETERS('filter ctxsys.null_filter LEXER mylex NOPOPULATE')
    PARALLEL 2;       Here my problem is:
    For the first time without creating index when I am trying to load 50000 files through SQL*LOADER conventional loading it is loading in 1 min 38 seconds.
    After that for creating index around : 11 min 12 seconds.
    But if I am loading another set of 10000 files after creating index, SQL*LOADER is taking considerable amount of time.
    For example :
    Index created with SYNC(ON COMMIT) : 28 min 45 sec
    Index created with SYNC(MANUAL) : 8 min 34 sec
    Index created with NOPOPULATE : 2 min 36 sec + 8 min 47 sec to rebuild the index.
    Please suggest me the best approach so that further load of files to the table also should take comparatively same time as the first load of 50000 files.
    Please suggest me how to create index to reduce load time.

    Hi all,
    I tried to load files using the below procedure also:
    CREATE OR REPLACE PROCEDURE load_file_to_my_docs (p_file_name  IN  my_files.name%TYPE) AS
      v_bfile      BFILE;
      v_clob       CLOB;
    BEGIN
      INSERT INTO my_files (id, name, doc)
      VALUES (my_files_seq.NEXTVAL, p_file_name, empty_clob())
      RETURN doc INTO v_clob;
      v_bfile := BFILENAME('SAMPLEDATA', p_file_name);
      Dbms_Lob.Fileopen(v_bfile, Dbms_Lob.File_Readonly);
      Dbms_Lob.Loadfromfile(v_clob, v_bfile, Dbms_Lob.Getlength(v_bfile));
      Dbms_Lob.Fileclose(v_bfile);
      COMMIT;
    END;
      But I found SQL*LOADER is loading fast compartive to this procedure.
    So please suggest me to reduce the time taking to load data once after creating TEXT index.

  • Color a column based on value in another column in tableview

    I am using a tableview iterator to display data in a bsp page. I want to color a cell in particular column (column 4), when a value in another column (column 2) on that same row is greater than 20. I can color the cell in column 2 but am not able to color the cell in column 4. How can I accomplish this?
    This is what I have. Looks like val1 is losing it's value.
    CASE p_column_index.
        WHEN 2.
          ASSIGN p_row_data_ref->* TO <row>.
          ASSIGN COMPONENT 'ZTGT' OF STRUCTURE <row> TO <col>.
          VAL = <col>.
          IF VAL GT '20'.
            val1 = p_row_index.
            p_style = 'celldesign:CRITICALVALUE_DARK'.
          ENDIF.
        WHEN 4.
            if p_row_index = val1.
              p_style = 'celldesign:CRITICALVALUE_DARK'.
            endif.
        WHEN OTHERS.
    do nothing
      ENDCASE.

    The reason val1 is "loosing its' value" is presumably because you have defined it in the method as a local variable. So each time you call the RENDER_CELL_START method it is is newly initialised. So if you make this an instance attribute it will retain its' contents across method calls.
    Cheers
    Graham Robbo

  • HELP: WHERE Clause based on value of the column

    I am selecting from a table as follows and want to have a where condition that is dependent of the value of the column, type of the current row.
    CREATE TABLE tbl (INT id, VARCHAR type, VARCHAR comment)
    I have 3 different values for the type column, EMPLOYEE, CUSTOMER, SUPPLIER. What I want is to have a where clause in my select that is based on the value of type.
    I tried the following but was not successful..
    SELECT * from tbl
    CASE
    WHEN type = 'EMPLOYEE' THEN
    WHERE comment LIKE '%employee%'
    WHEN type = 'CUSTOMER' THEN
    WHERE comment LIKE '%customer%'
    WHEN type = 'SUPPLIER' THEN
    WHERE comment LIKE '%supplier%'
    END
    I am not proficient with stored procedures so if you could please tell me how to do it with straight query, I would greatly appreciated it..
    Thank you,

    Or maybe this:
    SELECT *
      FROM tbl
    WHERE "COMMENT" LIKE
              CASE TYPE
                 WHEN 'EMPLOYEE'
                    THEN '%employee%'
                 WHEN 'CUSTOMER'
                    THEN '%customer%'
                 WHEN 'SUPPLIER'
                    THEN '%supplier%'
              END

  • Update/Insert into two fields based on value of one.

    How would I do the following in ADDT.
    Example:
    I have a database about dogs. When user completes form they make a selection from a recordset feed drop down box of breeds. Lets say they select "PUG" based on the selection two fields are populated from the same recordset size="small" and color="brown".
    I hope I've explained this well enough
    Thanks!
    Rich

    >>
    I think I understand. I'm using two forms One to select the item from a list. I'm passing that items value to the next page where I'm placing that value into a query which will give me the options available based on the query results?
    >>
    what I meant, is first have the user insert the new record and let him specify the desired "breed" already there -- the following page(s) will need to make sure that he´s going to update the newly inserted record with additional values, that´s why you should use the "SELECT dog_id FROM dog_table ORDER BY id DESC LIMIT 1" - query on page 2. However, once this new record had been clearly identified "by id", you can add whatever options available in the secondary table which are related to the "dog_id" (breed) that has been stored when inserting the new record. Maybe *I* don´t get it, lol ;-)
    >>
    I currently do this the dropdown value to a case statement that takes the value of the dropdown and determines the correct values for the database update
    >>
    OK, but when each dog just has one option
    (thought it were two ones: "color" and "size"), isn´t your existing dependant dropdown enough for specifying that "based on breed" option without having to use a hidden field at all ? Ah well, have you ever used ADDT´s / Kollections "dependant drop-down" wizard -- that should do it for one option
    >>
    hidden field that I need to update value based on what the value is above
    >>
    humm -- updating the value of a hidden field in the very same page then ? Never heard of this being possible apart from using some hand-made javascript.
    Guess I gotta ask my dog what it thinks about all that :-)
    Günter Schenk
    Adobe Community Expert, Dreamweaver

  • Update a column in each row in my table that have similar values in another column

    Hi All,
    I have a table in my DB.
    This table has values like this:
    Name
    Key
    a
    1
    a
    2
    a
    3
    a
    2
    b
    4
    b
    5
    b
    5
    I need to change the name to a different name for keys that are different. For same keys, the name must be same.
    Here I need to rename the 'a' to different name, but make sure that the 'a' that have 2 as the key have same name .
    Similarly, i've to rename the 'b' to different name , but make sure that the 'b' that have 5 as the key have the same name.
    How can I achieve this in sql? I dont know how to use cursor and complex queries, as i'm new to SQL.
    Please help
    Thanks,
    Vid
    Vidya Suryanarayana

    Ok. The output should be like this:
    Note here, that the names with same keys have same names.
    name
    key
    a1
    1
    a2
    2
    a3
    3
    a2
    2
    b1
    4
    b2
    5
    b2
    5
    Thanks,
    Vid
    Vidya Suryanarayana

  • Conditional inclusion of column cells based on value in another column?

    I was wondering if something like the following is possible -- I've looked through the forums and Numbers user guide but can't figure it out:
    Suppose I have a column A of sales figures, and columns B and C which basically have different attributes (say, color (yellow or green), size (small or large), and material (cotton or polyester)).
    I want to run basic statistics on various combinations: e.g. all yellow items regardless of size, all green cotton items regardless of size, all large yellow items regardless of material, etc.
    I want to be able to specify something like this:
    'Compute the average of every cell in column A where column B=="green" and column C=="large"'
    Is there a good way to go about doing this? Would I want to attack the problem using categories, sorting, and multiple tables? Or is there a way to conditionally include cell values from a range based on the value of that row's cell in another column?
    Thanks for any help.

    All I can think of to solve the quartile and median functions is to have another table of the same size as your original table that gets populated with just the items that match. Then you can do the quartile and median (and average) on that table. It's a one-at-a-time affair; you can only do one selection of size, color, and/or material at a time but you can get the median, mean, and quartiles of it. Of course, you could have multiple copies of this second table if you want to do more than one comparison at a time.
    In the attached file, unhide the hidden rows in Table 2 to see the formulas that do all the work.
    [files.me.com/pwb3/6hobt0.numbers.zip]
    Message was edited by: Badunit
    Message was edited by: Badunit

  • Issue in populating values in a column based on values in other columns

    I have a situation as below:
    Src        Tar             New tar
    AC001  TAC001  
    AC002  TAC001      AC002
    AC003  TAC001
    AC011  TAC011
    AC012  TAC011      AC012
    AC021  TCA021
    AC022  TCA021
    Now, wherw I have New target as AC002, I need to copy the same value to TAC001 which is the 1st and 3rd row. Similarly, I need to copy AC012 to 4th record. And my last 2 rows will be null as I do not have any values for TCA021..Any thoughts on this would be apprecated..
    Thanks in advance..

    Hi
    almost all is said so i tip you How to Fish (with Pictures) - wikiHow because it is good asset for future when you are hungry
    Read also http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions004.htm#SQLRF06174
    "Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. The group of rows is called a window and is defined by the analytic_clause. For each row, a sliding window of rows is defined. The window determines the range of rows used to perform the calculations for the current row. Window sizes can be based on either a physical number of rows or a logical interval such as time.
    Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE, GROUP BY, andHAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDERBY clause.
    Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates."

  • Filter column based on values in second column

    I have a 7 columns (A-G). I want to add a filter to return rows if the value in column D exists anywhere in column C (values in column D and C do not necessarily match).
    Is this possible? I tried creating a filter for column D based on column C using the 'Filter based on results of another request' functionality, but it did not work.
    Create/Edit Filter>Filter based on results of another request
    Column: column D
    Relationship: is equal to any
    Saved Request: same request
    Use values in Column: column C

    Okay, it looks like you are using the same query for both the main and subquery. That won't work.
    1) Create a query with one column, column D. Name it and save it.
    2) Now build your main report with all the columns you desire and on column C, apply the filter "based on results..." and have it point to column D of the subquery in step 1.

  • Insert into .. sql return incorrect value for 2 columns,sometime no value

    Hello,
    Oracle 10.2.0.3 , sol 10. (recently upgraded from oracle9i & sol8)
    sql query is used to populate a table. sometimes it is populating same values for all the records in 2 columns. Sometimes not populating or partially populating 1 other column. other times its running fine.
    SQL is not changed at all. When run again , it populates correctly.
    any help is highly appreciatied.
    --pooja                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    no ORA errors while execution. Its completing successfully.
    and its an intermittent issue. when the SQL is run manually its gives perfect results. Rerunnign the entire process is also fine. Conclusivly, data & SQL has no problem.
    its an insert into table <SQL>
    SQL contains left outer join.
    example:
    Expected output:
    1 john texas
    2 smith MA
    3 rob michigan
    Actual Output
    1 john texas
    2 smith texas
    3 rob texas

  • Merging rows into one row but into SEPARATE Columns

    Hello Gurus,
    I have searched alot on OTN and many other places, but no where I could get the solution of how can we merge rows into one row but separate column. For example
    Consider the below scenario
    "DEPARTMENT", "EMP","NAME","SUBJECT"
    "Electronics","1","Sam","LIC"
    "Electronics","2","Pam","VLSI"
    "Electronics","3","Tom","C"
    "Mech","1","Abu","Thermo"
    "Mech","4","Lina","Machines"Now, I need the output like
    Based on Department as Group By Clause
    "DEPARTMENT", "EMP1","NAME1","SUBJECT1","EMP2","NAME2","SUBJECT2","EMP3","NAME3","SUBJECT3"
    "Electronics","1","Sam","LIC","2","Pam","VLSI","3","Tom","C"
    "Mech","1","Abu","Thermo","4","Lina","Machines"
    The row data to be loaded into separate columns. Name of the column is not an issue... can be anythingIn all the forums which I went through I could find them loading into a single column, but not into respective separate columns.
    Any help would be much appreciated.
    Thanks

    848265 wrote:
    Frank,
    I saw your name nearly n number of times, as I went through many forums today... And the link which you have just posted, I went through it today afternoon.
    Could you please explain this bit taken from your dynamic pivot post.
    SELECT     DISTINCT
         ',     COUNT (CASE WHEN job = '''
    ||     job
    ||     ''' '     AS txt1
    ,     'THEN 1 END)     AS '
    ||     job
    ||     '_CNT'     AS txt2
    FROM     scott.emp
    ORDER BY     txt1;Many Thanks.You only need that when you need column aliases based on the actual data (and you explicitly said you don't need that) or when can't put an upper bound on the number of columns to be displayed. If that doesn't apply to this problem, then don't use any kind of dynamic SQL (like the code above); it makes the job much more difficult, less efficient and less robust.
    Here's what the code above is doing.
    If you were hard-coding a query that showed the number of people in each job, and you knew that the possible jobs were 'ANALYST', 'CLERK' and 'MANAGER', then you might hard-code a query like this:
    SELECT    deptno
    ,       COUNT (CASE WHEN job = 'ANALYST'  THEN 1 END)     AS analyst
    ,       COUNT (CASE WHEN job = 'CLERK'    THEN 1 END)     AS clerk
    ,       COUNT (CASE WHEN job = 'MANAGER'  THEN 1 END)     AS manager
    FROM       scott.emp
    GROUP BY  deptno
    ;If the jobs had different names, or if there were not 3 different jobs, then you would have to change the lines in the SELECT clause that start with ", COUNT ( CASE ...".
    The code you posted is from an example of dynamic SQL, where you first run a Preliminary Query . (What you posted above is, in fact, the complete preliminary query.) The output of that preliminary query is exactly the variable part of the real query, such as:
    ,       COUNT (CASE WHEN job = 'ANALYST'  THEN 1 END)     AS analyst
    ,       COUNT (CASE WHEN job = 'CLERK'    THEN 1 END)     AS clerk
    ,       COUNT (CASE WHEN job = 'MANAGER'  THEN 1 END)     AS managerYou then use this output as part of your main query. In other words, you can write something today that will generate exacrly as many columns as you need next year, with names from the data as it is next year. How? because you're not writing the full query today. The variable part will be written by the preliminary query when it runs next year.

Maybe you are looking for

  • Problem: JSP does not restore after downloading Excel.

    I have a "search.jsp" with a commandButton to generate excel. "Report.jsp" opens up in a new window when i click on this button by running below mentioned javascript. I can download Excel successfully by clicking on Download Excel link in report,jsp.

  • Creation of Multiple Similar Assets

    Hi experts, I need to ask if following is the best that can be done for splitting few assets of one class to another class or is a better solution exists for it Or is there any transaction/report that can create Multiple Similar Assets? Currently, we

  • Table control through screens

    hello friends, i was informed that i would be working on table controls through dialogue program, if any one has a sample code for tabel control through screens, plz post it here, so that , i can understand which command is to use for what, and what

  • Backup failed on PROD - Tivoli

    Dear all, i got the backup error on PROD - Tivoli , BKI9300E: Additional support information: Aborting 'send' operation. See previous error. BKI0405I: TDP waited 3 sec. for BRBACKUP in util_file_online communication. BKI0020I: End of program at: Thu

  • Combined files automatically re-organized by Bates number?

    I have a folder containing 1,373 PDF files, comprising what I think is approximately 7,400 pages. Each page was Bates stamped by a legal support company, but when they sent the CD containing said folder, all 1,373 files were organized by the file nam