XML DB: is it possible to get a row for each element in a container element?

I have an XML document containing a container element (collection). If I query, using an XPath expression, the contained elements I get a row for each container element with the contained element concatenated. Is it possible to get a row for each contained element?
I run this simple query:
select extract(xmltype('<colors><color>Red</color><color>Green</color></colors>')
, '/colors/color/text()').getstringval() from dual
And get this result:
EXTRACT(XMLTYPE('<COLORS><COLOR>RED</COLOR><COLOR>GREEN</COLOR></COLORS>'),'/COL
RedGreen
1 row selected.
What I would like to have is:
Red
Green
2 rows selected.
Wishful thinking or possible? Many thanks!

Sure. This is where our XMLSequence() function comes in. It allows you to treat the top-level nodes in a nodeset as if they were rows in a table when combined with the TABLE() operator. Here's an example.
First, to make the SQL look a little cleaner, I like to define a function like this:
create or replace function testdoc return xmltype as
begin
  return xmltype('<colors><color>Red</color><color>Green</color></colors>');
end;.
To break out the nodeset of <color> elements as a table, we use the following query:
select value(list_of_color_elements).extract('*/text()').getStringVal() as color
from TABLE( XMLSequence( extract(testdoc(),'/colors/color'))) list_of_color_elements.
Or, using the new-in-9.2 extractValue() operator so we don't have to remember the text() part:
select extractValue( value(list_of_color_elements), '.') as color
from TABLE( XMLSequence( extract( testdoc() ,'/colors/color'))) list_of_color_elements.
Here the TABLE(XMLSequence(...)) combo produces a table of XMLType, with one XMLType object in each row of the table.
In general, if the XMLType instance were coming from an XMLType table xmltab the query would look like this:
select extractValue( value(colors), '.') as color
from xmltab x, /* Important that this table comes earlier in the FROM clause! */
     TABLE( XMLSequence( extract( value(x),'/colors/color'))) colors.
And if the XMLType were instead in a column of XMLType named doc in a table xmltab, then we would have the syntax:
select extractValue( value(colors), '.') as color
from xmltab x, /* Important that this table comes earlier in the FROM clause! */
     TABLE( XMLSequence( extract( x.doc ,'/colors/color'))) colorsOnce you get the hang of it, you'll see that the combination of TABLE(XMLSequence()) to "shred" XML nodes into rows, and XMLAgg() to aggregate fragments of XML across multiple rows back into a single document, is quite powerful.

Similar Messages

  • Creating view to get first row for each table !!

    I am having tables(more than 10) which are related using foreign key and primary key relationship.
    Example:
    Table1:
    T1Prim T1Col1 T1Col2
    Table2
    T2For T2Prim T2Col1 T2Col2 T2Col3
    (here T2For will have value same as T1Prim and in my design it has same column name i.e. T1Prim)
    Table3
    T3For T3Prim T3Col1 T3Col2 T3Col3
    (here T3For will have value same as T2Prim)
    and so on.
    The data in the tables is like For table1 there will be one record, for table2 there will be one record and for table 3 there are more than one records.
    Can i view either the first record for each of them or all records from each of them by writing the following view.
    I have written a view like this:
    Create or replace view test (T1Prim,T1Col1, T1Col2,T2Prim,T2Col1 T2Col2, T2Col3, T3Prim,T3Col1, T3Col2, T3Col3)
    As
    Select
    Table1.T1Prim,
    Table1.T1Col1,
    Table1.T1Col2,
    Table2.T2Prim,
    Table2.T2Col1,
    Table2.T2Col2,
    Table2.T2Col3,
    Table3.T3Prim,
    Table3.T3Col1,
    Table3.T3Col2,
    Table3.T3Col3
    From
    Table1,
    Table2,
    Table3
    where
    Table1.Prim = Table2.For
    and Table2.Prim = Table3.For
    When i ran the select statement on the view I am not getting any data. Whereas there is data when select is ran on individual table.
    Can someone please tell me where i am goofing.
    Thanks in the anticipation that i will get some hint to solve this.
    Eagerly waiting for reply.
    Thanks !!

    I mean use a collection :
    Collection Methods
    A collection method is a built-in function or procedure that operates on collections and is called using dot notation. The methods EXISTS, COUNT, LIMIT, FIRST, LAST, PRIOR, NEXT, EXTEND, TRIM, and DELETE help generalize code, make collections easier to use, and make your applications easier to maintain.
    EXISTS, COUNT, LIMIT, FIRST, LAST, PRIOR, and NEXT are functions, which appear as part of an expression. EXTEND, TRIM, and DELETE are procedures, which appear as a statement. EXISTS, PRIOR, NEXT, TRIM, EXTEND, and DELETE take integer parameters. EXISTS, PRIOR, NEXT, and DELETE can also take VARCHAR2 parameters for associative arrays with string keys. EXTEND and TRIM cannot be used with index-by tables.
    For more information, see "Using Collection Methods".
    Syntax
    Text description of the illustration collection_method_call.gif
    Keyword and Parameter Description
    collection_name
    This identifies an index-by table, nested table, or varray previously declared within the current scope.
    COUNT
    COUNT returns the number of elements that a collection currently contains, which is useful because the current size of a collection is not always known. You can use COUNT wherever an integer expression is allowed.
    For varrays, COUNT always equals LAST. For nested tables, normally, COUNT equals LAST. But, if you delete elements from the middle of a nested table, COUNT is smaller than LAST.
    DELETE
    This procedure has three forms. DELETE removes all elements from a collection. DELETE(n) removes the nth element from an index-by table or nested table. If n is null, DELETE(n) does nothing. DELETE(m,n) removes all elements in the range m..n from an index-by table or nested table. If m is larger than n or if m or n is null, DELETE(m,n) does nothing.
    EXISTS
    EXISTS(n) returns TRUE if the nth element in a collection exists. Otherwise, EXISTS(n) returns FALSE. Mainly, you use EXISTS with DELETE to maintain sparse nested tables. You can also use EXISTS to avoid raising an exception when you reference a nonexistent element. When passed an out-of-range subscript, EXISTS returns FALSE instead of raising SUBSCRIPT_OUTSIDE_LIMIT.
    EXTEND
    This procedure has three forms. EXTEND appends one null element to a collection. EXTEND(n) appends n null elements to a collection. EXTEND(n,i) appends n copies of the ith element to a collection. EXTEND operates on the internal size of a collection. So, if EXTEND encounters deleted elements, it includes them in its tally. You cannot use EXTEND with index-by tables.
    FIRST, LAST
    FIRST and LAST return the first and last (smallest and largest) subscript values in a collection. The subscript values are usually integers, but can also be strings for associative arrays. If the collection is empty, FIRST and LAST return NULL. If the collection contains only one element, FIRST and LAST return the same subscript value.
    For varrays, FIRST always returns 1 and LAST always equals COUNT. For nested tables, normally, LAST equals COUNT. But, if you delete elements from the middle of a nested table, LAST is larger than COUNT.
    index
    This is an expression that must yield (or convert implicitly to) an integer in most cases, or a string for an associative array declared with string keys.
    LIMIT
    For nested tables, which have no maximum size, LIMIT returns NULL. For varrays, LIMIT returns the maximum number of elements that a varray can contain (which you must specify in its type definition).
    NEXT, PRIOR
    PRIOR(n) returns the subscript that precedes index n in a collection. NEXT(n) returns the subscript that succeeds index n. If n has no predecessor, PRIOR(n) returns NULL. Likewise, if n has no successor, NEXT(n) returns NULL.
    TRIM
    This procedure has two forms. TRIM removes one element from the end of a collection. TRIM(n) removes n elements from the end of a collection. If n is greater than COUNT, TRIM(n) raises SUBSCRIPT_BEYOND_COUNT. You cannot use TRIM with index-by tables.
    TRIM operates on the internal size of a collection. So, if TRIM encounters deleted elements, it includes them in its tally.
    Usage Notes
    You cannot use collection methods in a SQL statement. If you try, you get a compilation error.
    Only EXISTS can be applied to atomically null collections. If you apply another method to such collections, PL/SQL raises COLLECTION_IS_NULL.
    You can use PRIOR or NEXT to traverse collections indexed by any series of subscripts. For example, you can use PRIOR or NEXT to traverse a nested table from which some elements have been deleted.
    EXTEND operates on the internal size of a collection, which includes deleted elements. You cannot use EXTEND to initialize an atomically null collection. Also, if you impose the NOT NULL constraint on a TABLE or VARRAY type, you cannot apply the first two forms of EXTEND to collections of that type.
    If an element to be deleted does not exist, DELETE simply skips it; no exception is raised. Varrays are dense, so you cannot delete their individual elements.
    PL/SQL keeps placeholders for deleted elements. So, you can replace a deleted element simply by assigning it a new value. However, PL/SQL does not keep placeholders for trimmed elements.
    The amount of memory allocated to a nested table can increase or decrease dynamically. As you delete elements, memory is freed page by page. If you delete the entire table, all the memory is freed.
    In general, do not depend on the interaction between TRIM and DELETE. It is better to treat nested tables like fixed-size arrays and use only DELETE, or to treat them like stacks and use only TRIM and EXTEND.
    Within a subprogram, a collection parameter assumes the properties of the argument bound to it. So, you can apply methods FIRST, LAST, COUNT, and so on to such parameters. For varray parameters, the value of LIMIT is always derived from the parameter type definition, regardless of the parameter mode.
    Examples
    In the following example, you use NEXT to traverse a nested table from which some elements have been deleted:
    i := courses.FIRST; -- get subscript of first element
    WHILE i IS NOT NULL LOOP
    -- do something with courses(i)
    i := courses.NEXT(i); -- get subscript of next element
    END LOOP;
    In the following example, PL/SQL executes the assignment statement only if element i exists:
    IF courses.EXISTS(i) THEN
    courses(i) := new_course;
    END IF;
    The next example shows that you can use FIRST and LAST to specify the lower and upper bounds of a loop range provided each element in that range exists:
    FOR i IN courses.FIRST..courses.LAST LOOP ...
    In the following example, you delete elements 2 through 5 from a nested table:
    courses.DELETE(2, 5);
    In the final example, you use LIMIT to determine if you can add 20 more elements to varray projects:
    IF (projects.COUNT + 20) < projects.LIMIT THEN
    -- add 20 more elements
    Related Topics
    Collections, Functions, Procedures
    http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/13_elems7.htm#33054
    Joel P�rez

  • Get sample row for each recrd.

    I have a table EMP
    having columns as as
    GROUP , GROUP_NAME, EMPNO , EMP_NAME
    Having following data
    GROUP , GROUP_NAME, EMPNO , EMP_NAME
    1,eng1,1,ZZ
    1,eng1,2,RR
    2,eng2,2,RR
    3,eng3,3,MM
    3,eng3,2,RR
    I need to select a samle of each record for group field. (each samle for group 1 ,2 and 3 ....(it is unlimited))
    Output like:
    1,eng1,1,ZZ
    2,eng2,2,RR
    3,eng3,3,MM
    How to get it?
    If some thing is not clear reply me back.

    change the order by in the window clause to dbms_random.value:
      1  with t as(
      2      select 1 GROUP1 ,'eng1' GROUP_NAME, 1 EMPNO , 'ZZ' EMP_NAME
      3      from dual union all
      4      select 1,'eng1',2,'RR'
      5      from dual union all
      6      select 2,'eng2',2,'RR'
      7      from dual union all
      8      select 3,'eng3',3,'MM' from
      9      dual union all
    10      select 3,'eng3',2,'RR'
    11      from dual)
    12      SELECT group1, group_name, emp_name
    13        FROM (SELECT group1,
    14                     ROW_NUMBER () OVER
    15                     (PARTITION BY group1
    16                     ORDER BY dbms_random.value /*---give RANDOM value*/) rn,
    17                     group_name, emp_name
    18               FROM t)
    19*     WHERE rn = 1
    SQL> /
        GROUP1 GROU EM
             1 eng1 RR
             2 eng2 RR
             3 eng3 MM
    SQL> /
        GROUP1 GROU EM
             1 eng1 ZZ
             2 eng2 RR
             3 eng3 RR
    SQL> /
        GROUP1 GROU EM
             1 eng1 ZZ
             2 eng2 RR
             3 eng3 RR
    SQL> /Amiel

  • Is it possible to get a refund for a case i bought at the store but its not an apple product?

    I bought a kate spade plastic case at the store 2 months ago and even the first day of having it on my iPhone I had multiple issues with it. However, I couldn't return it because I was away at school. I went into the Apple store and asked about the possibility of getting a refund for the case but they said it was a third party product and to contact the manufacturer. I called kate spade and since i wanted a refund and purchased at the apple store there was nothing they could do and to ask the apple store for my money back because thats where I purchased it. Am I ever going to get a refund and what should I do at this point?
    Thanks
    Sara

    http://support.apple.com/kb/HT1933
    Regards.

  • Any possibility of getting automatic alerts for Bdocs?

    Hi all,
    Any possibility of getting automatic alerts for Bdocs Instead of doing manual bdoc monitoring using SMW02/SMW01.
    For example Sales order is created in CRM, transferred to R/3. bcoz of some problems order is not posted successfully in R/3 . Any possibility of getting automatic alerts for Bdocs Instead of doing manual (checking)  bdoc monitoring using SMW02/SMW01.
    If yes, Plz let me know how to procees automatic alerts for Bdocs .
    Thanks in advance,
    P.V

    Hi,
    This is very much possible and though a very simple transaction:
    Tcode: SMW00 Error Handler
    Select 'Error Action for a Specific BDoc Type'
    Press Execute
    Press Maintain Configuration button or press F9
    In the next screen, you can specify what BDOC types you want the alert to come for, what status of BDOc should the alert come for, the error action can be set as Workflow or Mail
    Select 'Mail'
    Select the Typr of reciopient (e.g. B Sap User)
    Enter the recipient (User name)
    Check Express for an alert to popup
    Cehck always Process
    SAVE and Execute
    These settings will help you get an email and an alert popup whenever a BDOc fails
    Thsi must work for you
    Kindly reward with points in case helpful
    Sharif

  • Is it possible to get custom eartips for the Apple In-ear headphones?

    A year or so ago I purchased the Apple In-ear headphones. I use them primarily in the car when my brother plays his music through the car stereo while I'm watching a movie on my iPod Touch or my MacBook Pro. They have very good isolation, but are uncomforable and it is very hard to get them to fit in my ears properly as well as keeping them from working themselves out of my ears. This is with me using the small eartips as the large eartips don't fit in my ears at all and the medium eartips make my ears hurt more than the small eartips along with not fitting as well.
    I think custom eartips may be the best solution to my quandry.
    Is it possible to get custom eartips for my Apple In-ear headphones?
    If so, where can I get custom eartips for my Apple In-ear headphones?

    i would definitely try amazon.com, im sure there are some earips on there that are fit to work with apple in-ear headphones, hope this helps!

  • My on off button on my iPhone isn't working and it has been for several months but i went to the apple store today and the warranty was only 16 days over is it possible to get it fixed for free

    my on off button on my iPhone isn't working and it has been for several months but i went to the apple store today and the warranty was only 16 days over is it possible to get it fixed for free

    If the genius at the Apple Store did not offer repair under warranty then NO
    12 months is 12months asume you did not have AppleCare

  • We need to buy Adobe Framemaker version 11. The distributor is only able to provide us with version 12. Can someone suggest me how is it possible to get the license for ver 11 serial  key after purchasing ver 12 and also how to get the download details ?

    We need to buy Adobe Framemaker version 11. The distributor is only able to provide us with version 12. Can someone suggest me how is it possible to get the license for ver 11 serial  key after purchasing ver 12 and also how to get the download details ?   Urgent response will be helpful.D

    Adobe Support helped us with a similar query. We ended up with exactly what you need.

  • Is there a way to get the details for each hit in the portal database WCR_WEBCONTENTSTAT?

    Hi,
    I need to get the details for each user hit.
    Apparently, this table has the IMPRESSIONS column which returns the total number of hitcounts and VISITS which counts the number of unique user who accesses the portal. What I am trying to look for is to get all the details per hitcount. I need to find out how many time a specific user accessed a specific page or iview.
    I also used the table WCR_USERPAGEUSAGE, which I get the information of the users counted in the VISITS column in the first table.
    I could not get the specific user per hit.
    Please enlighten me if this is possible and how to do this?
    Thanks!

    Hi Catherine,
    Why not use the portal activity report iView?
    In the portal activity report iView the 3rd option allows you to choose a page for example and see
    the user who accessed it and how many times.
    Thanks and BR,
    Saar

  • Qry:How to get different price for each price list (variable area) in order

    1-How to get different price for each price list (variable area) in order for sale. for the opportunity to display and select multiple prices.
    2- I add a location store from a table in line item and I want to see this area in order,.
    I 'm created 2 field location(item line and order), 1 table location
    I tried this for exemple : select $ [userfieldlocation.OITW]

    Thanks Suda for your answer,
    the Formatted Search for prices is OK, but for the Item locations in warehouse this is not so simple,     
    I must have several (at least 2) locations for the item in the Warehouse and a track of this location and search possibilities.
    read carefully and imagine how (Management warehouse locations)
    I added a user table '@Location' who linked to a user field 'U_Location in Item master data --> lnventory data  line and an ather user field 'U_Location' in sales order
    I met the value of location in the table (list of locations for any warehouse), I select the location of each item while receiving merchandise in the user field of inventory data line (Item M data) and this value appears in the sales order 'U_Location' user field ( only the location value in the default warehouse for this Item)
    or
    create an user field 'location' in Good receipt PO to fill it while receiving merchandise that appears in the sales order to give possibility to find/select the location of the item at this order and in Item master data
    I think we will use all these tables
    @LOCATION
    PDN1
    OITM
    OITW
    OWHS
    RDR1
    Juste a another question : where you found this and What is: ' 38.1.0 '
    Is it in document (System information):Item=38 Pane=1 ??
    Thanks,
    Ouchen

  • How to Get Missing Dates for Each Support Ticket In My Query?

    Hello -
    I'm really baffled as to how to get missing dates for each support ticket in my query.  I did a search for this and found several CTE's however they only provide ways to find missing dates in a date table rather than missing dates for another column
    in a table.  Let me explain a bit further here -
    I have a query which has a list of support tickets for the month of January.  Each support ticket is supposed to be updated daily by a support rep, however that isn't happening so the business wants to know for each ticket which dates have NOT been
    updated.  So, for example, I might have support ticket 44BS which was updated on 2014-01-01, 2014-01-05, 2014-01-07.  Each time the ticket is updated a new row is inserted into the table.  I need a query which will return the missing dates per
    each support ticket.
    I should also add that I DO NOT have any sort of admin nor write permissions to the database...none at all.  My team has tried and they won't give 'em.   So proposing a function or storable solution will not work.  I'm stuck with doing everything
    in a query.
    I'll try and provide some sample data as an example -
    CREATE TABLE #Tickets
    TicketNo VARCHAR(4)
    ,DateUpdated DATE
    INSERT INTO #Tickets VALUES ('44BS', '2014-01-01')
    INSERT INTO #Tickets VALUES ('44BS', '2014-01-05')
    INSERT INTO #Tickets VALUES ('44BS', '2014-01-07')
    INSERT INTO #Tickets VALUES ('32VT', '2014-01-03')
    INSERT INTO #Tickets VALUES ('32VT', '2014-01-09')
    INSERT INTO #Tickets VALUES ('32VT', '2014-01-11')
    So for ticket 44BS, I need to return the missing dates between January 1st and January 5th, again between January 5th and January 7th.  A set-based solution would be best.
    I'm sure this is easier than i'm making it.  However, after playing around for a couple of hours my head hurts and I need sleep.  If anyone can help, you'd be a job-saver :)
    Thanks!!

    CREATE TABLE #Tickets (
    TicketNo VARCHAR(4)
    ,DateUpdated DATETIME
    GO
    INSERT INTO #Tickets
    VALUES (
    '44BS'
    ,'2014-01-01'
    INSERT INTO #Tickets
    VALUES (
    '44BS'
    ,'2014-01-05'
    INSERT INTO #Tickets
    VALUES (
    '44BS'
    ,'2014-01-07'
    INSERT INTO #Tickets
    VALUES (
    '32VT'
    ,'2014-01-03'
    INSERT INTO #Tickets
    VALUES (
    '32VT'
    ,'2014-01-09'
    INSERT INTO #Tickets
    VALUES (
    '32VT'
    ,'2014-01-11'
    GO
    GO
    SELECT *
    FROM #Tickets
    GO
    GO
    CREATE TABLE #tempDist (
    NRow INT
    ,TicketNo VARCHAR(4)
    ,MinDate DATETIME
    ,MaxDate DATETIME
    GO
    CREATE TABLE #tempUnUserdDate (
    TicketNo VARCHAR(4)
    ,MissDate DATETIME
    GO
    INSERT INTO #tempDist
    SELECT Row_Number() OVER (
    ORDER BY TicketNo
    ) AS NROw
    ,TicketNo
    ,Min(DateUpdated) AS MinDate
    ,MAx(DateUpdated) AS MaxDate
    FROM #Tickets
    GROUP BY TicketNo
    SELECT *
    FROM #tempDist
    GO
    -- Get the number of rows in the looping table
    DECLARE @RowCount INT
    SET @RowCount = (
    SELECT COUNT(TicketNo)
    FROM #tempDist
    -- Declare an iterator
    DECLARE @I INT
    -- Initialize the iterator
    SET @I = 1
    -- Loop through the rows of a table @myTable
    WHILE (@I <= @RowCount)
    BEGIN
    --  Declare variables to hold the data which we get after looping each record
    DECLARE @MyDate DATETIME
    DECLARE @TicketNo VARCHAR(50)
    ,@MinDate DATETIME
    ,@MaxDate DATETIME
    -- Get the data from table and set to variables
    SELECT @TicketNo = TicketNo
    ,@MinDate = MinDate
    ,@MaxDate = MaxDate
    FROM #tempDist
    WHERE NRow = @I
    SET @MyDate = @MinDate
    WHILE @MaxDate > @MyDate
    BEGIN
    IF NOT EXISTS (
    SELECT *
    FROM #Tickets
    WHERE TicketNo = @TicketNo
    AND DateUpdated = @MyDate
    BEGIN
    INSERT INTO #tempUnUserdDate
    VALUES (
    @TicketNo
    ,@MyDate
    END
    SET @MyDate = dateadd(d, 1, @MyDate)
    END
    SET @I = @I + 1
    END
    GO
    SELECT *
    FROM #tempUnUserdDate
    GO
    GO
    DROP TABLE #tickets
    GO
    DROP TABLE #tempDist
    GO
    DROP TABLE #tempUnUserdDate
    Thanks, 
    Shridhar J Joshi 
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • Get the Count for each row

    I'm trying to get the count for each row to total count for each month
    Something like this
    Hardware     |      Jan
    Monitors       |       5
    Processors   |      137
    Printers        |      57
    etc........
    How can I write a query for this. I can get the Hardware column but don't know how to get the next column.

    If you can provide more data like sample input DML statements it would have been wonderful..
    Assuming is , you need a pivot. Here is an article on basic Pivot..
    http://sqlsaga.com/sql-server/how-to-use-pivot-to-transform-rows-into-columns-in-sql-server/
    something like this may be..
    DECLARE @Input TABLE
    Hardware VARCHAR(20),
    [Date] VARCHAR(20)
    INSERT INTO @Input VALUES('Monitor', '01/01/2014'), ('CPU', '01/01/2014'), ('Monitor', '01/03/2014')
    , ('ABC', '01/01/2014'),('Monitor', '02/01/2014')
    ;WITH CTE AS
    SELECT Hardware, LEFT(DATENAME(M, [Date]),3) AS [MonthName] FROM @Input
    SELECT *
    FROM
    SELECT Hardware, [MonthName], COUNT(Hardware) AS Count FROM CTE GROUP BY Hardware, [MonthName]) a
    PIVOT (MAX([Count]) FOR [MonthName] IN ([Jan], [Feb])) pvt
    Please mark as answer, if this has helped you solve the issue.
    Good Luck :) .. visit www.sqlsaga.com for more t-sql code snippets and BI related how to articles.

  • Getting the first row for each group

    Hi Everyone,
    I have a query which returns a number of rows, all of which are valid. What I need to do is to get the first row for each group and work with those records.
    For example ...
    client flight startairport destairport stops
    A fl123 LGW BKK 2
    A fl124 LHR BKK 5
    B fl432 LGW XYZ 7
    B fl432 MAN ABC 8
    .... etc.
    I would need to return one row for Client A and one row for Client B (etc.) but find that I can't use the MIN function because it would return the MIN value for each column (i.e. mix up the rows). I also can use the rownum=1 because this would only return one row rather than one row per group (i.e. per client).
    I have been investigating and most postings seem to say that it needs a second query to look up the first row for each grouping. This is a solution which would not really be practical because my query is already quite complex and incorporating duplicate subqueries would just make the whole thing much to cumbersome.
    So what I really new is a "MIN by group" or a "TOP by group" or a "ROWNUM=1 by group" function.
    Can anyone help me with this? I'm sure that there must be a command to handle this.
    Regards and any thanks,
    Alan Searle
    Cologne, Germany

    Something like this:
    select *
    from (
       select table1.*
       row_number() over (partition by col1, col2 order by col3, col4) rn
       from table1
    where rn = 1In the "partition by" clause you place what you normally would "group by".
    In the "order by" clause you define which will have row_number = 1.
    Edit:
    PS. The [url http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/functions004.htm#i81407]docs have more examples on using analytical functions ;-)
    Edited by: Kim Berg Hansen on Sep 16, 2011 10:46 AM

  • TSQL Get Previous values for each group by

    Dear Friends,
    I have a problem with my TSQL statment. 
    I need to get previous value for each day and specific unit. Everything goes fine if I have always 2 unit in each day. But if same day has just one unit or less, I cannot have the previous value in the current record.
    The Output is this one:
    SK_DAY SK_UNIT
    VALUE VALUE_PREVIUS_DAY
    20131112 2
    30.00 NULL
    20131112 3
    34.00 NULL
    20131113 2
    40.00 30.00
    20131113 3
    45.00 34.00
    20131114 2
    50.00 40.00
    I dont have the second record for 2013-11-14, because in this date I just have value for unit 2.
    The final output should include the record:
    20131114 3
    0 45.00
    The Statment I have is:
    SELECT MAIN.SK_DAY, MAIN.SK_UNIT, SUM(MAIN.VALUE) AS VALUE
     SELECT SUM(VND1.VALUE) AS VALUE
     FROM FCT_TEST VND1
     WHERE CONVERT(DATE,CONVERT(VARCHAR(10),VND1.SK_DAY))>=DATEADD(dd,-1,CONVERT(DATE,CONVERT(VARCHAR(10),MAIN.SK_DAY)))
    AND CONVERT(DATE,CONVERT(VARCHAR(10),VND1.SK_DAY))<CONVERT(DATE,CONVERT(VARCHAR(10),MAIN.SK_DAY))
    AND VND1.SK_UNIT=MAIN.SK_UNIT
    ) AS VALUE_PREVIUS_DAY
    FROM FCT_TEST MAIN
    GROUP BY SK_DAY, MAIN.SK_UNIT
    SQL CREATE SCRIPT:
    CREATE TABLE [dbo].[FCT_TEST](
    [SK_DAY] [int] NOT NULL,
    [SK_UNIT] [int] NOT NULL,
    [VALUE] [decimal](18, 2) NULL,
     CONSTRAINT [PK_FCT_TEST] PRIMARY KEY CLUSTERED 
    [SK_DAY] ASC,
    [SK_UNIT] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    Thank you!!!
    PPSQL

    Thank you Kalman,
    But my problem is not with date! Fortunately I have dates for all days.
    The problem is for dimension tables like UNITS that I dont have values for all days, and when I try to get the previous value for previous day and each unit I dont have records. 
    20131112
    2
     30.00
    NULL
    20131112
    3
     34.00
    NULL
    20131113
    2
     40.00
    30.00
    20131113
    3
     45.00
    34.00
    20131114
    2
     50.00
    40.00
    20131114
    3
     0
    45.00 [I NEED THIS RECORD AS IS]
    Could you help me??
    Thank you!!

  • Get frequent data for each column of a table

    What is the best way to get the most frequent data in each column of a table.
    we have around 25 tables and each table has around 20 columns , so rather than writing group by for each column of table , is there any easy way to find this?
    example we have table
    Column A       Column B         Column C
    Apple             Monday             Red
    orange            Tuesday            Green
    Apple              Monday            Red
    Lemon            Wednesday       Green
    Apple               Thursday         Red
    in this table, column A's frequnt data is Apple , column B's frequent data is Monday , Column C's frequnt data is Red
    Apple 3          Monday 2                  Red 3
    Orange 2        Tuesday 1                 Green 2
    Lemon 1          Wednesday 1         
                          Thursday 1
    Group by kind of query will give this result, but with 20 tables each having 20 - 30 columns if we need similar kind of result ..  is there any way to get this data.

    Hi,
    GROUP BY (using aggregate functions) is the best way to do what you described.
    PIVOT and UNPIVOT are probably what you'd want in this case.  The phrase "GROUP BY" may not actually appear in your code, but you'll essentially be doing a GROUP BY.
    Analytic functions (rather than aggregate functions) can do the job, too, but they'll be less efficient.  Analytic functions get you results about the groups, without losing each row's identify, but in this case, losing each row's identity is eactly what you want to do.  You only want 'Apple' to appear 1 time, not 3 times.
    The fact that you need to do the same query on 20 different tables suggests that there's something wrong with your table design.  Wouldn't it be better to have 1 big table, with a new column that has 20 unique values instead?
    I hope this answers your question.
    If not, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved, so that the people who want to help you can re-create the problem and test their ideas.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Simplify the problem as much as possible.  For example, instead of posting a problem with 20 tables, each having 25 columns, post a similar problem involving, say, 2 tables, each with 3 columns.
    Always say which version of Oracle you're using (for example, 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

Maybe you are looking for

  • What's wrong with the JSP file??Urgent Help Request

    I have run some JSP files using Apache Tomcat 4.0 but I see many similar error message for the JSP files when running on the IE. I don't whether I should install some other software or components or just program errors in the JSP files. The error mes

  • External Keyboard being recognized as Internal Keyboard

    I have a Microsoft Wireless 6000 v2 external keyboard. I have installed the Intellitype software and in the past I have had this setup working great! The problem I'm now facing is that somewhere during my latest reinstall of Leopard (hard drive crash

  • Some links and social network features not active in user profile service for some users in sharepoint 2013

    Hi everyone, I installed user profile service and synchronize. When I go to my site by administrator user every things is OK. But when I login by another user the my site is look like this Please guide me to resolve this problem. Thanks in advance.

  • CRM 5.0 certification query?

    Hi, I just spoke to SAP UK regarding CRM Marketing certification CR600. They do CRM 5.0( not CR 4.0) & no prerequesite like certifaction in base customisation ( though it is advisable ). So we can straightway do CR600 I have been practising in CRM 4.

  • BT disconnection and ensuring the correct address.

    I've sold my home in Bolton and I've scheduled to have my phone line cut off on the 29th August, which is the completion date for my house buyers to move in (at 2pm). What is the actual time that the line will be disconnected, i.e. is it terminated a