ONE ROW PER TYPE

Hi ,
I have go three tables. personnel, Personnel_degree, and code_types
here is how they are related . Personnel Stores the person informations like id,name etc. Personnel_degree stores personnel_id, degree_id, , degree_date and code_types stores the code_id and code_name , personnel can belinked to personnel_degree though personel_id and the personnel_degree can be linked though the code_id . Each person can have BS, MS OR PHD , the can have any one of them , two of them or all of them . I want to write a sql query so it brings me the person name and the highest degree he has earned. if John has a PHD degree, then he should not appear under master and BS. Similalry if SAMS has got MS & BS , he should not appear under BS , he should appear under MS only.
Thanks
-Feroz

You will need to work out your join conditions. The "Magic" is in the decode statement.
I did it with a decode because I did not know what version you are running, so this will work whether your at 9i or not
Example:
SELECT f_name, DECODE(MAX(DECODE(degree, 'PHD', 3, 'MS', 2, 'BS', 1)), 1, 'BS', 2, 'MS', 3, 'PHD') degree
FROM test
GROUP BY f_name

Similar Messages

  • Parse column with csv string into table with one row per item

    I have a table (which has less than 100 rows) - ifs_tables that has two columns: localtable and Fields. Localtable is a table name and Fields contains a subset of columns from that table. Fields is a comma delimited list:  'Fname,Lname'. It looks like
    this:
    localtable         fields
    =========  =============
    customertable   fname,lname
    accounttable     type,accountnumber
    Want to end up with a new table that has one row per column. It should look like this:
    TableName             ColumnName
    ============ ==========
    CustomerTable        Fname
    CustomerTable        Lname
    AccountTable          Type
    AccountTable          AccountNumber
    Tried this code but have two issues (1) My query using the Splitfields functions gets "Subquery returned more than 1 value" (2) some of my Fields has hundreds of collumns in the commas delimited list. It will returns "Msg 530, Level 16, State
    1, Line 8. The statement terminated. The maximum recursion 100 has been exhausted before statement completion.maxrecursion greater than 100." Tried adding OPTION (maxrecursion 0) in the Split function on the SELECT statment that calls the CTE, but
    the syntax is not correct.
    Can someone help me to get this sorted out? Thanks
    DROP FUNCTION [dbo].[SplitFields]
    go
    CREATE FUNCTION [dbo].[SplitFields]
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
    RETURNS TABLE
    AS
    RETURN
    WITH Split(stpos,endpos)
    AS(
    SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
    UNION ALL
    SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
    FROM Split
    WHERE endpos > 0
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
    'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split --OPTION ( maxrecursion 0);
    GO
    IF OBJECT_ID('tempdb..#ifs_tables') IS NOT NULL DROP TABLE #ifs_tables
    SELECT *
    INTO #ifs_tables
    FROM (
    SELECT 'CustomerTable' , 'Lname,Fname' UNION ALL
    SELECT 'AccountTable' , 'Type,AccountNumber'
    ) d (dLocalTable,dFields)
    IF OBJECT_ID('tempdb..#tempFieldsCheck') IS NOT NULL DROP TABLE #tempFieldsCheck
    SELECT * INTO #tempFieldsCheck
    FROM
    ( --SELECT dLocaltable, dFields from #ifs_tables
    SELECT dLocaltable, (SELECT [Data] FROM dbo.SplitFields(dFields, ',') ) from #ifs_tables
    ) t (tLocalTable, tfields) -- as Data FROM #ifs_tables
    SELECT * FROM #tempFieldsCheck

    Try this
    DECLARE @DemoTable table
    localtable char(100),
    fields varchar(200)
    INSERT INTO @DemoTable values('customertable','fname,lname')
    INSERT INTO @DemoTable values('accounttable','type,accountnumber')
    select * from @DemoTable
    SELECT A.localtable ,
    Split.a.value('.', 'VARCHAR(100)') AS Dept
    FROM (SELECT localtable,
    CAST ('<M>' + REPLACE(fields, ',', '</M><M>') + '</M>' AS XML) AS String
    FROM @DemoTable) AS A CROSS APPLY String.nodes ('/M') AS Split(a);
    Refer:-https://sqlpowershell.wordpress.com/2015/01/09/sql-split-delimited-columns-using-xml-or-udf-function/
    CREATE FUNCTION ParseValues
    (@String varchar(8000), @Delimiter varchar(10) )
    RETURNS @RESULTS TABLE (ID int identity(1,1), Val varchar(8000))
    AS
    BEGIN
    DECLARE @Value varchar(100)
    WHILE @String is not null
    BEGIN
    SELECT @Value=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN LEFT(@String,PATINDEX('%'+@Delimiter+'%',@String)-1) ELSE @String END, @String=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN SUBSTRING(@String,PATINDEX('%'+@Delimiter+'%',@String)+LEN(@Delimiter),LEN(@String)) ELSE NULL END
    INSERT INTO @RESULTS (Val)
    SELECT @Value
    END
    RETURN
    END
    SELECT localtable ,f.Val
    FROM @DemoTable t
    CROSS APPLY dbo.ParseValues(t.fields,',')f
    --Prashanth

  • Hacking application id equals() to allow more than one row per "primary key"

    I have a read only entity whose primary key is not the real primary key
    on the underlying table. The result is that I get more than one row per
    "primary key". This is what I want. However KODO will not allow me do
    it, because I am storing the collection in a HashSet() and the equals()
    method on the application id object ensures that this set contains no
    duplicates (as defined by the application id). At least thats how it
    seems to behave.
    So, I have hacked the equals() method to do this:
    public boolean equals (Object ob)
    if (this == ob)
    return true;
    // Doing this because we expect more than one row from
    // REF_CODES for the same domain/shortCode combination.
    // This is ok to do (I guess?) as long as we are only
    // doing selects using this class.
    return false;
    Will this hack have any side effects? Is there another option? Like
    using a list collection? Is so, which collections are supported?
    Thanks,
    Mike.

    The "primary key" I am using it already a compound key of two columns.
    The real key on the underlying table is a three column key. But the
    problem is that the table represents two different application level
    entities. I could deal with it when I was hand-writing SQL (I could do
    a distinct for example) but now I am relying on foreign key
    relationships since I moved to JDO. Not sure what to do. Best solution
    is to rework the table, but there is a lot of legacy code (that other
    teams use and maintain) relying on this table. I guess I'll use the
    weekend for inspiration ;-)
    Steve Kim wrote:
    This sounds like a dangerous operation. Even if this works now, I
    cannot promise future compatibility... and in fact may result in bad
    data (for example in caching both at the PM and PMF level) Is there no
    other field that you can reference as part of the primary key? Primary
    Keys can be multi columned (e.g. last_name, soc_sec_number)
    Mike Hogan wrote:
    I have a read only entity whose primary key is not the real primary
    key on the underlying table. The result is that I get more than one
    row per "primary key". This is what I want. However KODO will not
    allow me do it, because I am storing the collection in a HashSet() and
    the equals() method on the application id object ensures that this set
    contains no duplicates (as defined by the application id). At least
    thats how it seems to behave.
    So, I have hacked the equals() method to do this:
    public boolean equals (Object ob)
    if (this == ob)
    return true;
    // Doing this because we expect more than one row from
    // REF_CODES for the same domain/shortCode combination.
    // This is ok to do (I guess?) as long as we are only
    // doing selects using this class.
    return false;
    Will this hack have any side effects? Is there another option? Like
    using a list collection? Is so, which collections are supported?
    Thanks,
    Mike.

  • OCI - Array-Fetch vs. One-row-per-fetch

    Hello guys,
    i have a question about the OCI and the possibilities about fetches.
    Is it possible to get only one row per fetch without setting the array size to 1?
    I have a third party application that shows this behaviour which i have rebuild in sqlplus.
    SQL> create table mytest (a number);
    SQL> begin
      2  for i in 1 .. 1500 loop
      3  insert into mytest values (i);
      4      end loop;
      5  end;
      6  /
    PL/SQL procedure successfully completed.
    SQL> commit;
    Commit complete.
    SQL> set autotrace traceonly;
    -- Now with the default array size of 15 with sqlplus
    SQL> select * from mytest;
         118  consistent gets
         101  SQL*Net roundtrips to/from client
         1500  rows processed
    -- Now with a bigger array size (150)
    SQL> set arraysize 150
    SQL> select * from mytest;
         17  consistent gets
         11  SQL*Net roundtrips to/from client
         1500  rows processed
    -- Now the behaviour of the third party application
    SQL> set arraysize 1
    SQL> select * from mytest;
         757  consistent gets
         751  SQL*Net roundtrips to/from client
         1500  rows processed
    SQL> set arraysize 2
    SQL> select * from mytest;
         757  consistent gets
         751  SQL*Net roundtrips to/from client
         1500  rows processedThe third party application is a c program and i can not take a look at the code.
    So as you can see the consistent gets are the same with arraysize 1 and 2. The sql statement which is executed of the c-program is returning a huge amount of data and it seems like it is run with arraysize 1 or 2 or it is executing a different OCI call.
    So now is my question:
    Which methods does the OCI interface provide to recieve (fetch) data?
    - Is it only array fetching (like sqlplus do) or is it possible to return only one row per fetch with a specific call.
    I can speed up the query by setting the bigger array-size in sqlplus .. but i want to point the programers to the possibilities with the OCI.
    Thanks and Regards
    Stefan

    The following call in OCI can be used to control the fetched rows
    MAX_PREFETCH_ROWS is number of rows you want to fetch in one round trip.
    (void) OCIAttrSet((dvoid *)DBctx->stmthp, (ub4) OCI_HTYPE_STMT,
    (dvoid *)&MAX_PREFETCH_ROWS,(ub4)sizeof(MAX_PREFETCH_ROWS),(ub4) OCI_ATTR_PREFETCH_ROWS, DBctx->errhp);

  • How to pivot horizontally Author names, and group by Book title. One row per book with multiple authors

    I have 3 tables - Book, Author, BookAuthorReference
    A book can have multiple authors, and when I do straight query I get multiple rows per book
    SELECT <columns>
    FROM Book b, Author a, BookAuthorReference ba
    where ba.BookId = b.BookId and
    ba.AuthorId = a.AuthorId
    I want to get the results as ONE row per book, and Authors separated by commas, like:
    SQL 2008 internals book    Paul Randal, Kimberly Tripp, Jonathan K, Joe Sack...something like this
    Thank you in advance

    This can by done by straying into XML land. The syntax is anything but intuitive, but it works. And moreover, it is guaranteed to work.
    SELECT b.Title, substring(a.Authors, 1, len(a.Authors) - 1) AS Authors
    FROM   Books b
    CROSS  APPLY (SELECT a.Author + ','
                  FROM   BookAuthorReference ba
                  JOIN   Authors a ON a.AuthorID = ba.AuthorID
                  WHERE  ba.BookID = a.BookID
                  ORDER  BY ba.AuthorNo
                  FOR XML PATH('')) AS a(Authors)
    Erland Sommarskog, SQL Server MVP, [email protected]

  • SQL Report - PDF Report Printing. How to show one row per page?

    Hello
    I have successfully created a simple SQL Report.
    Than I enabled Report Printing to PDF (default Report Layout).
    Export to PDF is working good by default.
    Now I want to see one report row per one PDF page. Is it possible?
    How I can change the amount of rows per PDF page using default report layout?
    I tried to create a User Layout with MSWord Plugin. it's quite suitable for data forms.
    But I still did not find a way around for my question.

    I would create an User Layout (.rtf) with MSWord. Load your XML data and use the table wizzard to put the fields in your document.
    Put this code after your last field and before the 'E' (= <?end for-each?> tag):
    <?split-by-page-break:?>

  • Can an Excel Report with Multivalue Custom field list report on one row per task

    I have a ECF Multi Value field (MVF) at the Task Level and have created a report.  In Excel it wants to add it as a Pivotable, which makes sense and I end up with a row for each MVF.  If a Task has 3 MV selected there are 3 rows returned.
    I want to see if it will return only one row (row per task). 
    Example of Result Required
    PTask name , MVf Value1, MVF Value2, MVF Value 3.
    Build Car             X                                    
    X
    Build Bike            X                     X
    Is it possible?  is there something in my SQL Query I can do or is there something in Excel I can configure?
    Result being Returned
    PTask name , MVf Value1, MVF Value2, MVF Value 3.
    Build Car             X                                    
    Build Car                                                    X
    Build Bike            X                    
    Build Bike                                 X
    SQL Query
    SELECT
    MSP_EpmProject_UserView.ProjectOwnerName,
    MSP_EpmProject_UserView.ProjectName,
    MSP_EpmTask_UserView.TaskName,
    MSP_EpmLookupTable.MemberFullValue AS [Item],
    Iif(MSP_EpmLookupTable.MemberFullValue LIKE 
    '%' + 'CPT' + '%','X','') AS [CPT],
    Iif(MSP_EpmLookupTable.MemberFullValue LIKE 
    '%' + 'TS' + '%','X','') AS [TS],
    Iif(MSP_EpmLookupTable.MemberFullValue LIKE 
    '%' + 'CSAs' + '%','X','') AS [CSAs],
    Iif(MSP_EpmLookupTable.MemberFullValue LIKE 
    '%' + 'EM' + '%','X','') AS [EM],
    Iif(MSP_EpmLookupTable.MemberFullValue LIKE 
    '%' + 'RS' + '%','X','') AS [RS],
    Iif(MSP_EpmLookupTable.MemberFullValue LIKE 
    '%' + 'IS' + '%','X','') AS [IS]
    FROM
    MSP_EpmProject_UserView INNER JOIN
    MSP_EpmTask_UserView ON
    MSP_EpmProject_UserView.ProjectUID = MSP_EpmTask_UserView.ProjectUID
    LEFT OUTER JOIN
    [MSPCFTASK_Service Areas_AssociationView] ON
    MSP_EpmTask_UserView.TaskUID = [MSPCFTASK_Service Areas_AssociationView].EntityUID
    LEFT OUTER JOIN
    MSP_EpmLookupTable ON
    [MSPCFTASK_Service Areas_AssociationView].LookupMemberUID = MSP_EpmLookupTable.MemberUID
    WHERE datalength(MSP_EpmLookupTable.MemberFullValue) > 0
    Andrew Payze

    Hi Andrew,
    I'm not a developer, but I found something in my documentation that could help you. This is a SQL store procedure that returns in an Excel pivot table something like below (GR_test6 being a project and values in the next column being multivalue project ECF
    values).
    SELECT proj.ProjectName,
    lt.MemberFullValue AS 'VLookupField'
    FROM dbo.MSP_EpmProject_UserView AS proj
    LEFT OUTER JOIN [dbo].[MSPCFPRJ_ProjectECF_AssociationView] AS MVassoc -- view for multi value field
    ON proj.ProjectUID = MVassoc.EntityUID
    LEFT OUTER JOIN dbo.MSP_EpmLookupTable AS lt
    ON MVassoc.LookupMemberUID = lt.MemberUID
    order by ProjectName asc
    Hope this helps.
    Guillaume Rouyre - MBA, MCP, MCTS

  • Returning one row per group

    I apologize if this is a duplicate of some other post, but I'm not finding this exact scenario.
    Assume that I have a table that looks like this:
    select * from PROD_TABLE
    PROD DESCRIPTION
    1234 CANDLES
    1234 CANDLE
    1235 BRAKE PADS
    1235 BRAKE PAD
    (Yes, I know, I know, but it's for a POC, so dirty data will be cleaned up later.)
    What I'd like to do is create a select statement that returns two rows from this table, one row for Prod 1234, one row for Prod 1235, and I DON'T CARE which description is returned for the corresponding Prod. For the POC, it's just not important which one is returned.
    How can I craft the select statement?

    try this
    SQL> with t as (select 1234 prod, 'CANDLES' dec from dual union all
      2  select 1234 ,'CANDLE' dec from dual union all
      3  select 1235 ,'BRAKE PADS' dec from dual union all
      4  select 1235 ,'BRAKE PAD' dec from dual)
      5  SELECT prod, DEC
      6    FROM ( SELECT a.*
      7                , ROW_NUMBER ( ) OVER ( PARTITION BY prod ORDER BY prod ) rn
      8            FROM t a )
      9   WHERE rn = 1
    10  /
          PROD DEC
          1234 CANDLES
          1235 BRAKE PADS
    SQL>

  • Function returning more than one row in type

    SQL> create or replace package types
    2 as
    3 type cursorType is ref cursor;
    4 end;
    5 /
    Package created.
    SQL> create or replace function sp_ListEmp return types.cursortype
    2 as
    3 l_cursor types.cursorType;
    4 begin
    5 open l_cursor for select rowid from emp;
    6 return l_cursor;
    7* end;
    8 /
    Function created.
    SQL> select sp_listEmp from dual;
    SP_LISTEMP
    CURSOR STATEMENT : 1
    CURSOR STATEMENT : 1
    ROWID
    AAAHW7AABAAAMUiAAB
    AAAHW7AABAAAMUiAAC
    AAAHW7AABAAAMUiAAD
    AAAHW7AABAAAMUiAAE
    AAAHW7AABAAAMUiAAF
    AAAHW7AABAAAMUiAAG
    AAAHW7AABAAAMUiAAH
    AAAHW7AABAAAMUiAAI
    AAAHW7AABAAAMUiAAJ
    when i execute select * from emp where rowid in(select sp_listEmp from dual);
    I am not getting output Please help me
    Message was edited by:
    Oracle_Friend

    Pipelined function can help you :
    SCOTT@demo102> ed
    Wrote file afiedt.buf
      1* create or replace type EmpRowid as table of varchar2(64);
    SCOTT@demo102> /
    Type created.
    SCOTT@demo102> ed
    Wrote file afiedt.buf
      1  create or replace function emp_rowid
      2    RETURN EmpRowid
      3    PIPELINED
      4  IS
      5  BEGIN
      6    FOR x IN (select rowid from emp)
      7    LOOP
      8      PIPE ROW( x.rowid );
      9    END LOOP;
    10    RETURN;
    11* END;
    SCOTT@demo102> /
    Function created.
    SCOTT@demo102> select * from table( emp_rowid );
    COLUMN_VALUE
    AAAMfPAAEAAAAAgAAA
    AAAMfPAAEAAAAAgAAB
    AAAMfPAAEAAAAAgAAC
    AAAMfPAAEAAAAAgAAD
    AAAMfPAAEAAAAAgAAE
    AAAMfPAAEAAAAAgAAF
    AAAMfPAAEAAAAAgAAG
    AAAMfPAAEAAAAAgAAH
    AAAMfPAAEAAAAAgAAI
    AAAMfPAAEAAAAAgAAJ
    AAAMfPAAEAAAAAgAAK
    AAAMfPAAEAAAAAgAAL
    AAAMfPAAEAAAAAgAAM
    AAAMfPAAEAAAAAgAAN
    14 rows selected.
    SCOTT@demo102> select *
      2  from emp
      3  where rowid in (select column_value from table( emp_rowid ));
         EMPNO ENAME      JOB              MGR HIREDATE        SAL       COMM
        DEPTNO
          7369 SMITH      CLERK           7902 17/12/80       8000
            20
          7499 ALLEN      SALESMAN        7698 20/02/81      16000        300
            30
          7521 WARD       SALESMAN        7698 22/02/81      12500        500
            30
         EMPNO ENAME      JOB              MGR HIREDATE        SAL       COMM
        DEPTNO
          7566 JONES      MANAGER         7839 02/04/81      29750
            20
          7654 MARTIN     SALESMAN        7698 28/09/81      12500       1400
            30
          7698 BLAKE      MANAGER         7839 01/05/81      28500
            30
         EMPNO ENAME      JOB              MGR HIREDATE        SAL       COMM
        DEPTNO
          7782 CLARK      MANAGER         7839 09/06/81      24500
            10
          7788 SCOTT      ANALYST         7566 19/04/87      30000
            20
          7839 KING       PRESIDENT            17/11/81      50000
            10
         EMPNO ENAME      JOB              MGR HIREDATE        SAL       COMM
        DEPTNO
          7844 TURNER     SALESMAN        7698 08/09/81      15000          0
            30
          7876 ADAMS      CLERK           7788 23/05/87      11000
            20
          7900 JAMES      CLERK           7698 03/12/81       9500
            30
         EMPNO ENAME      JOB              MGR HIREDATE        SAL       COMM
        DEPTNO
          7902 FORD       ANALYST         7566 03/12/81      30000
            20
          7934 MILLER     CLERK           7782 23/01/82      13000
            10
    14 rows selected.
    SCOTT@demo102> You can add parameters to the function for restrict the result.
    Nicolas.

  • Query to display one row per group based on highest value

    I have the following table and I want to be able to create a query that displays only the highest number based on a group. (see below)
    Acode
    aname
    anumber
    a
    Jim
    40
    a
    Jim
    23
    a
    Jim
    12
    b
    Sal
    42
    b
    Sal
    12
    b
    Sal
    3
    Acode
    aname
    anumber
    a
    Jim
    40
    b
    Sal
    42

    Multiple ways
    using aggregation
    SELECT Acode,aname,MAX(anumber) AS anumber
    FROM table
    GROUP BY Acode,aname
    using subquery
    SELECT Acode,aname,anumber
    FROM table t
    WHERE NOT EXISTS (
    SELECT 1
    FROM table
    WHERE Acode = t.Acode
    AND aname = t.aname
    AND anumber > t.anumber
    using analytical function
    SELECT Acode,aname,anumber
    FROM
    SELECT *,ROW_NUMBER() OVER (PARTITION BY Acode, aname ORDER BY anumber DESC) AS Rn
    FROM table
    )t
    WHERE Rn = 1
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • How just return one row of a one to many join..

    So I have a one to many join where the SMOPERATOR table has data I need however it has a couple of rows that match the JOIN condition in there. I just need to return one row. I think this can be accomplished with a subquery in the join however have not been able to come up with the right syntax to do so.
    So:
    SELECT "NUMBER" as danumber,
    NAME,
    SMINCREQ.ASSIGNMENT,
    SMOPERATOR.PRIMARY_ASSIGNMENT_GROUP,
    SMOPERATOR.WDMANAGERNAME,
    SMINCREQ.owner_manager_name,
    SMINCREQ.subcategory, TO_DATE('01-'||TO_CHAR(open_time,'MM-YYYY'),'DD-MM-YYYY')MONTHSORT,
    (CASE WHEN bc_request='f' THEN 'IAIO'
    WHEN (bc_request='t' and substr(assignment,1,3)<>'MTS') THEN 'RARO'
    WHEN (bc_request='t' and substr(assignment,1,3)='MTS') THEN 'M'
    ELSE 'U' end) as type
    from SMINCREQ
    left outer join SMOPERATOR on SMINCREQ.assignment=SMOPERATOR.primary_assignment_group
    WHERE SMINCREQ.owner_manager_name=:P170_SELECTION and SMOPERATOR.wdmanagername=:P170_SELECTION
    AND open_time BETWEEN to_date(:P170_SDATEB,'DD-MON-YYYY') AND to_date(:P170_EDATEB,'DD-MON-YYYY')
    AND
    (bc_request='f' and subcategory='ACTIVATION' and related_record<>'t')
    OR
    (bc_request='f' and subcategory<>'ACTIVATION')
    OR
    (bc_request='t' and substr(assignment,1,3)<>'MTS')
    order by OPEN_TIMe

    Hi,
    This sounds like a Top-N Query , where you pick N items (N=1 in this case) off the top of an orderded list. I think you want a separate ordered list for each assignment; the analytic ROW_NUMBER function does that easily.
    Since you didn't post CREATE TABLE and INSERT statements for your sample data, I'll use tables from the scott schema to show how this is done.
    Say you have a query like this:
    SELECT       d.dname
    ,       e.empno, e.ename, e.job, e.sal
    FROM       scott.dept  d
    JOIN       scott.emp   e  ON   d.deptno = e.deptno
    ORDER BY  dname
    ;which produces this output:
    DNAME               EMPNO ENAME      JOB              SAL
    ACCOUNTING           7934 MILLER     CLERK           1300
    ACCOUNTING           7839 KING       PRESIDENT       5000
    ACCOUNTING           7782 CLARK      MANAGER         2450
    RESEARCH             7876 ADAMS      CLERK           1100
    RESEARCH             7902 FORD       ANALYST         3000
    RESEARCH             7566 JONES      MANAGER         2975
    RESEARCH             7369 SMITH      CLERK            800
    RESEARCH             7788 SCOTT      ANALYST         3000
    SALES                7521 WARD       SALESMAN        1250
    SALES                7844 TURNER     SALESMAN        1500
    SALES                7499 ALLEN      SALESMAN        1600
    SALES                7900 JAMES      CLERK            950
    SALES                7698 BLAKE      MANAGER         2850
    SALES                7654 MARTIN     SALESMAN        1250Now say you want to change the query so that it only returns one row per department, like this:
    DNAME               EMPNO ENAME      JOB              SAL
    ACCOUNTING           7782 CLARK      MANAGER         2450
    RESEARCH             7876 ADAMS      CLERK           1100
    SALES                7499 ALLEN      SALESMAN        1600where the empno, ename, job and sal columns on each row of output are all taken from the same row of scott.emp, though it doesn't really matter which row that is.
    One way to do it is to use the analytic ROW_NUMBER function to assign a sequence of unique numbers (1, 2, 3, ...) to all the rows in each department. Since each sequence startw with 1, and the numbers are unique within a department, there will be exactly one row per departement that was assigned the numebr 1, and we''ll display that row.
    Here's how to code that:
    WITH     got_r_num     AS
         SELECT     d.dname
         ,     e.empno, e.ename, e.job, e.sal
         ,     ROW_NUMBER () OVER ( PARTITION BY  d.dname
                                   ORDER BY          e.ename
                           )         AS r_num
         FROM     scott.dept  d
         JOIN     scott.emp   e  ON   d.deptno = e.deptno
    SELECT       dname
    ,       empno, ename, job, sal
    FROM       got_r_num
    WHERE       r_num     = 1
    ORDER BY  dname
    ;Notice that he sub-query got_r_num is almost the same as the original query; only it has one additional column, r_num, in the SELECT clause, and the sub-qeury does not have an ORDER BY clause. (Sub-queries almost never have an ORDER BY clause.)
    The ROW_NUMBER function must have an ORDER BY clause. In this example, I used "ORDER BY ename", meaning that, within each department, the row with the first ename (in sort order) will get r_num=1. You can use any column, or expression, or expressions in the ORDER BY clause. You muight as well use something consistent and predictable, like ename, but if you really wanted arbitrary numbering you could use a constant in the analytic ORDER BY clause, e.g. "ORDER BY NULL".

  • Concatenate strings from more rows into one row.

    Hi,
    what's the name of that analytical function (or connect by) that
    would return strings from more rows as one row concatenated. i.e.:
    (I know this is possible using regular pipelined functions.)
    ROW1:   STR1
    ROW2:   STR2
    ROW3:   STR3
    select tadah().... from ...
    result:
    ROW1: STR1 STR2 STR3Thanks.

    Hi,
    Here's a basic example of SYS_CONNECT_BY_PATH.
    The query below produces one row of output per department, containing a list of the employees in that department, in alphabetioc order.
    WITH     got_rnum     AS
         SELECT     ename
         ,     deptno
         ,     ROW_NUMBER () OVER ( PARTITION BY  deptno
                                         ORDER BY          ename
                              ) AS rnum
         FROM     scott.emp
    --     WHERE     ...          -- Any filtering goes here
    SELECT     deptno
    ,     LTRIM ( SYS_CONNECT_BY_PATH ( ename
                                  , ','     -- Delimiter, must never occur in ename
               )          AS ename_list
    FROM     got_rnum
    WHERE     CONNECT_BY_ISLEAF     = 1
    START WITH     rnum          = 1
    CONNECT BY     rnum          = PRIOR rnum + 1
         AND     deptno          = PRIOR deptno
    ;Output:
    .   DEPTNO ENAME_LIST
            10 CLARK,KING,MILLER
            20 ADAMS,FORD,JONES,SCOTT,SMITH
            30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARDThe basic CONNECT BY query would produce one row per employee, for example:
    .   DEPTNO ENAME_LIST
            10 ,CLARK
            10 ,CLARK,KING
            10 ,CLARK,KING,MILLER
            20 ,ADAMS
            20 ,ADAMS,FORD
    ...The WHERE clause: <tt>WHERE CONNECT_BY_ISLEAF = 1</tt> means that we'll only see the last row for every department.
    SYS_CONNECT_BY_PATH (which is a row function, by the way, not an analytic fucntion) puts a delimiter (',' in the example above) before every item on the list, including the first one.
    The query above uses LTRIM to remove the delimiter at the very beginning.
    WM_COMCAT (or the equivalent user-defined STRAGG, which you can copy from AskTom) is much more convenient if order is not important.

  • SQL query - select one row from each date group

    Hi,
    I have data as follows.
    Visit_Date Visit_type Consultant
    05/09/2009 G name1
    05/09/2009 G name2
    05/09/2009 G name3
    06/09/2009 I name4
    07/09/2009 G name5
    07/09/2009 G name6
    How to select data as follows
    05/09/2009 G name1
    06/09/2009 G name4
    07/09/2009 G name5
    i.e one row from every visit_date
    Thanks,
    MK Nathan
    Edited by: k_murali on Oct 7, 2009 10:44 PM

    Are you after this (one row per date per visit_type)
    with dd as (select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name1' Consultant from dual
                union all
                select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name2' Consultant from dual
                union all
                select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name3' Consultant from dual
                union all
                select to_date('06/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name4' Consultant from dual
                union all
                select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name5' Consultant from dual
                union all
                select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name6' Consultant from dual
                union all
                select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'F' Visit_type, 'name7' Consultant from dual)
    select trunc(visit_date) visit_date, visit_type, min(consultant)
    from   dd
    group by trunc(visit_date), visit_type
    order by trunc(visit_date);
    VISIT_DAT V MIN(C
    09/MAY/09 G name1
    09/JUN/09 G name4
    09/JUL/09 G name5
    09/JUL/09 F name7or are you after only one row per date?:
    with dd as (select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name1' Consultant from dual
                union all
                select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name2' Consultant from dual
                union all
                select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name3' Consultant from dual
                union all
                select to_date('06/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name4' Consultant from dual
                union all
                select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name5' Consultant from dual
                union all
                select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name6' Consultant from dual
                union all
                select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'F' Visit_type, 'name7' Consultant from dual)
    select trunc(visit_date) visit_date, min(visit_type) visit_type, min(consultant)
    from   dd
    group by trunc(visit_date)
    order by trunc(visit_date);
    VISIT_DAT V MIN(C
    09/MAY/09 G name1
    09/JUN/09 G name4
    09/JUL/09 F name5

  • Looping over multiple rows of data to output one row

    My query is giving me the appropriate data, but I need to
    only have one row per 'MANAGER' in my output - not one for each
    'JOB'. Now the output looks like this:
    manager 1 ... period 1 $ .... period 2 $ .... period 3 $
    manager 1... period 1 $ .... period 2 $ .... period 3 $
    manager 1... period 1 $ .... period 2 $ .... period 3 $
    manager 1... period 1 $ .... period 2 $ .... period 3 $
    manager 2... period 1 $ .... period 2 $ .... period 3 $
    manager 2... period 1 $ .... period 2 $ .... period 3 $
    manager 2... period 1 $ .... period 2 $ .... period 3 $
    manager 2... period 1 $ .... period 2 $ .... period 3 $
    It needs to be:
    Manager 1 ... total period 1 $ .... total period 2 $ ....
    Manager 2 ... total period 1 $ .... total period 2 $ ....
    Any help would be wonderful. I am really new at something
    this complex. Thanks!!!

    To fix your immediate issue, you need to order and group by
    manager, not MPR_ID (whatever that is).
    What is dm_id? Use descriptive names!
    Anyway, change the ORDER BY clause to:
    ORDER BY
    RR.LastName+', '+RR.FirstName, <!--- Or maybe dm_id??
    --->
    AA.MPR_ID
    Then change the first <cfoutput> to:
    <cfoutput query="production" group="Rep_name">

  • If I add artwork by dragging a jpg to the artwork area after selecting several rows, in some instances a single icon is created in the flipper;  in others one is created for each song. Why? How can I get one image per album every time?

    If I add artwork by dragging a jpg to the artwork area after selecting several rows, in some instances a single icon is created in the flipper;  in others one is created for each song. Why? How can I get one image per album every time?

    If I add artwork by dragging a jpg to the artwork area after selecting several rows, in some instances a single icon is created in the flipper;  in others one is created for each song. Why? How can I get one image per album every time?

Maybe you are looking for

  • Configuration for extensions filter while using Tomahawk 1.1.6

    Hello, I am using Sun RI 1.1 with tomahawk 1.1.6 and using facelets. I am stucked with following error: SEVERE: Error Rendering View[/pages/employees-calendar.xhtml] java.lang.IllegalStateException: ExtensionsFilter not correctly configured. JSF mapp

  • Continuous Bluetooth Inquiry J2ME

    I'm trying to develop a midlet that will continuously inquiry for nearby devices. I want to test if it's possible to inquiry a device while he is inquiring too. I have done this continuous inquiry by doing an initial startInquiry and then calling the

  • Purchase Order - Release Startegies; Inconsistency error

    Dear all, I am changing our release startegy for the purchase orders. Therfore I added two characteristics: - Plant (Table EKKO and Field WERKS) - Material Number The problem is that I get the following error message: "Inconsistent characteristic val

  • Microsoft Word Doc not opening - EPS Import message

    Suddenly whenever I try to open a word doc I get the following message: There is not enough memory or disk space to run the converter "EPS Import". What in the world does this mean?? There is still 78 of 148 GB of memory available so clearly not a di

  • LENOVO T400 BSOD help

    it has been like 2 month since I got this laptop, and I just got a BSOD twice today, which said, DRIVER_IRQL_NOT_LESS_OR_EQUAL 0x000000D1  and some other numbers. Any help on this? also I do ont know why, but sometimes when i start the cpu, it will f