Ho to do a select distinct with many colums

Hi,
How can I do a select distinct from many colums so that I get only one result for each case.
e.g if I want to select from employees table.
Hire_date,salary,job_id,department_id

This could be one of the solutions !
SQL> SELECT * FROM DS;
DEPTNO JOB             ID
    101 MANAGER        500
    101 ANALYST        520
    105 ANALYST        520
    101 MANAGER        501
    102 MANAGER        501
    102 PROGRAMMER     605
    102 PROGRAMMER     501
    103 CLERK          605
8 rows selected.
SQL> select case when row_number() over(partition by deptno order by deptno)>1
  2  then null else deptno end "DEPTNO",
  3  case when row_number() over(partition by job order by job) >1
  4  then null else job    end "JOB",
  5  case when row_number() over(partition by id  order by id )>1
  6  then null else id  end "ID" from ds;
DEPTNO JOB             ID
    101 ANALYST        520
        MANAGER        500
                       501
    102
                       605
        PROGRAMMER
    103 CLERK
    105
8 rows selected.

Similar Messages

  • Need help with select distinct with group by

    RDBMS 10gr2
    I am trying achieve having a select distinct with a order by and after looking on the internet and trying different examples, I have been unsucessful.
    Here is the code working (not sorting - I wish to sort by pps.last_name however I can't seem to get it to work).
    select distinct pps.last_name || ', ' ||pps.first_name || ' ' ||pps.middle_initial || '.' d,
           emple_no r
      from cobr.vw_pps_payroll pps,
           projman pm
    where term_date is null
       and department = '0004400000'
       and pm.eid != pps.emple_no

    SQL> SELECT   ename || '-' || empno, sal
      2      FROM emp_test
      3  ORDER BY ename;
    ENAME||'-'||EMPNO                                                                         SAL
    BLAKE-7698                                                                              20000
    CLARK-7782                                                                              20000
    DAVID-7699                                                                              20000
    FORD-7902                                                                                6000
    JONES-7566                                                                               5950
    KING-7839                                                                               10000
    SCOTT-7788                                                                               6000
    7 ligne(s) sélectionnée(s).
    SQL>

  • SELECT DISTINCT With OPEN cursor FOR

    Hello.
    I have the following procedure. All it does is open a cursor for an SQL string passed into it, and return the open cursor.
    PROCEDURE sp_execute_dynamic (hold_input_string IN CLOB,
    hold_cursor OUT hold_cursor_type) IS
    BEGIN
    OPEN hold_cursor FOR TO_CHAR(hold_input_string);
    END sp_execute_dynamic;
    It works fine except when I perform SELECT DISTINCT. I get the following error.
    SQL> declare
    2 TYPE hold_cursor_type IS REF CURSOR;
    3 hold_cursor hold_cursor_type;
    4 hold_object_name VARCHAR2(1024);
    5 hold_object_type VARCHAR2(1024);
    6 begin
    7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
    name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
    8 loop
    9 fetch hold_cursor into hold_object_name, hold_object_type;
    10 exit when hold_cursor%NOTFOUND;
    11 dbms_output.put_line('Object Name = '||hold_object_name||' Object Type = '||hold_object_type);
    12 end loop;
    13 end;
    14 /
    declare
    ERROR at line 1:
    ORA-01007: variable not in select list
    ORA-06512: at line 9
    It does the same thing with SELECT UNIQUE or SELECT with a GROUP BY. Can anyone tell me why this happens and what I could to to work around it?
    Thanks
    Chris

    see at line 7 you are selecting only one column and at line 9you are fetching into two variables
    7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
    name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
    8 loop
    9 fetch hold_cursor into hold_object_name, hold_object_type;
    HTH

  • SELECT DISTINCT with JOIN

    Hi,
    how Do I write this select in rigth way in ABAP
    SELECT ska1ktopl AS ktopl ska1saknr AS saknr
        t370k_t~eartx AS eartx
        INTO  TABLE lt_ska1 FROM ska1
        JOIN (SELECT DISTINCT damage_gl FROM  zzpm_cost_elem )  ON ska1saknr = zzpm_cost_elemdamage_gl.
    The problem with the select "SELECT DISTINCT damage_gl FROM  zzpm_cost_elem " which I have to put table name instead of it
    What should I do ?
    Thx

    Hi Friend ,
    Please see this example  how you can use the select DISTINCT statement
    DATA: ITAB TYPE STANDARD TABLE OF SPFLI,
          WA LIKE LINE OF ITAB.
    DATA: LINE(72) TYPE C,
          LIST LIKE TABLE OF LINE(72).
    LINE = ' CITYFROM CITYTO '.
    APPEND LINE TO LIST.
    SELECT DISTINCT (LIST)
           INTO CORRESPONDING FIELDS OF TABLE ITAB
           FROM SPFLI.
    IF SY-SUBRC EQ 0.
      LOOP AT ITAB INTO WA.
        WRITE: / WA-CITYFROM, WA-CITYTO.
      ENDLOOP.
    ENDIF.
    Regards,

  • SELECT DISTINCT with LINQ

    Hey,
    I am trying to perform a SELECT DISTINCT COL1, COL2, COL3 FROM VIEW WHERE CONDITION using LINQ with ODAC 112030 but I get different results.
    C#:
    var s1 = context.Select(v=>new { v.COL1, v.COL2, v.COL3}).Where(...).Distinct();
    Any ideas?

    Hey,
    I think this way works - with anonymous types:
    context.Entity.Where(...).Select(ent => new { col1 = ent.COL1, ... }).Distinct();.
    You can also do context.Entity.Select("distinct it.COL1, it.COL2").Where("..."); but one should be careful to add all necessary columns in select statement.
    Edited by: 917334 on Jun 7, 2012 7:11 AM

  • I have several disks with many comedy routines;I want to select a few from each disk and combine them to one disk for my personal use.How?

    I have several disks with many comedy routines;I want to select a few from each disk to make one single disk for my personal use.How?

    Copy the routines into a new folder on your hard drive. Then burn the folder to a new blank disc using Disk Utility.

  • When i use view as list in finder and open a folder with many files i cant right click with mouse without selecting or highlighting a file....i just want to right click to paste an item or create a new folder...what can i do?

    When i use view as list in finder and open a folder with many files i cant right click with mouse without selecting or highlighting a file....i just want to right click to paste an item or create a new folder...what can i do?

    Thx for that im gonna try it....but is there a way to do it without using toolbar or cmd-c...? i mean using only the mouse?why does it have to highlight the file even though i click a bit next to it....?using icon view i can right click next to the folder and i wont have a problem but with list view that i prefer using it will highlight the whole row.....and i dont find free space to right click cause i got many files

  • Help! Howto use the join function in a query with select distinct ?

    Hi!
    I have 2 tables. I want to select only 1 painting of each artists.
    select distinct idartist
    from tbl_artworks
    where blah blah blah
    order by rand()
    how does the "join" function work for add: name, lastname, title, image and much more... i try... but i fail...
    tbl_artists
    idartist
    name
    lastname
    1
    Paul
    Gaugain
    2
    Vincent
    Van Gogh
    3
    Pablo
    Picasso
    tbl_artworks
    idartwork
    idartist
    title
    image
    1
    1
    days of gods
    image1.jpg
    2
    2
    sunflower
    image2.jpg
    3
    3
    Dora maar au chat
    image3.jpg
    4
    2
    Sky
    image4.jpg
    5
    3
    La vie
    image5.jpg

    Getting a single random image for each probably requires a combination of sql and cf.  It would take someone smarter than me to do it with sql alone.  I would probably try something like this:
    1.  Run a database query that gets all the images from all the artists.
    2.  Run a Q of Q that gets a distinct list of artist ids.
    3.  Loop through that list and run a Q of Q to get all the images for that artist.
    4.  Still in that loop, use randrange (1 to the recordcount) to select a random record from your Q of Q

  • Select distinct problem with muliple join tables, help needed

    Hi,
    I have two main tables. Each has its of sub joined tables.
    guest_id_for_reservation connects two major tables. This has
    to be that way
    because my guest may change the room status from single to
    double (and the
    similar exceptional requests).
    guests reservation
    guest_id_for_reservation
    countrytable hoteltable
    delegationtable roomtype
    I form a query. I want to select distinct those results. But
    it does not
    work.
    If I do not include any table related to reservation table
    and its sub
    joined tables (disregarding guest_id_for_reservation), it
    works.
    Is there a specific syntax for select distinct of this type
    or any
    workaround.?
    Thank you
    Hakan

    Hi I'm still battling with this - have connected the AX to my Imac via ethernet and it shows up fine in Airport Utility. Status light is green and it says its set up to connect to my existing wireless network using wireless connection. Security in Network Preferences is the same for both: WPA2 Personal.
    So I don't think there's a problem with the AX, and my current wireless network (BT Home Hub) is working fine.
    And when I restore factory settings Airport Utility can see the AX before updating settings so the wireless side of AX must work too.
    I'm figuring it must be something about the settings that mean AU can't see it anymore. But I can't work out what, since security is the same.
    Any ideas would be great!

  • Problems with "Select Distinct" Statement

    Hi... I've a little problem with my SQL Statement...
    I've a Table in a DataBase with Solds of the Month... the fields are: vta_fecha, vta_prod, vta_total, vta_mesa.
    I've to Select only the distincts fields of vta_prod... selected by vta_fecha and vta_mesa...
    My code is like this:         try{
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                conec = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/POOL/Data/BaseDat.MDB");
                state = conec.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);try{
                rec = state.executeQuery("Select DISTINCT vta_prod, vta_fecha, vta_mesa from Ventas where vta_fecha = #" + Fecha_q + "# And vta_mesa = 0");           
                rec.first();
                int x = 0;
                while (rec.isAfterLast()==false){
                    x++;
                    rec.next();
                rec.first();
                if (x > 0){
                    Productos = new String[x];
                    Total_Vta = new int[x];
                    Cant_Prod = new int[x];
                    x = 0;
                    while (rec.isAfterLast() == false){
                        Productos[x] = rec.getString("vta_prod");
                        rec.next();
                        x++;
                else{
                    Productos = new String[0];
                    Total_Vta = new int[0];
                    Cant_Prod = new int[0];
            }catch(Exception e){JOptionPane.showMessageDialog(null,e.getMessage());}Now, in the Table I have only 3 diferents vta_prod, but this Statement returns 9 Rows... and I don't know why...
    Please help me...
    Regards...

    I don�t have a complete picture because I don�t know what values you are passing in the select and I don�t know your column types but this is what I think is happening from what you have shared.
    You may have misunderstood what the DISTINCT keyword does.
    The DISTINCT keyword applies to the full set of columns in the select (not just the first column). So in your case it would be equivalent to:
    SELECT vta_prod, vta_fecha, vta_mesa
    FROM Ventas
    WHERE ...
    GROUP BY by vta_prod, vta_fecha, vta_mesa
    So, it doesn't matter that you only have 3 distinct vta_prod values if you have multiple values being returned in the other columns. The vta_mesa column can only a return a single value as �0�. That leaves the vta_fecha column which is probably a date/time column and is probably the column that is returning the three other distinct values (one date with three distinct times).
    (3 vta_prod) x (3 vta_fecha) x (1 vta_mesa) or 3x3x1 = 9 rows
    So find a way to strip the time from vta_fecha in your select statement and your SQL should return the results you expect. I�m not an Access expect but I think I remember you can use something like the �Convert� or �DatePart� functions to make that happen (check your documentation to be sure)..
    A couple of asides;
    1) You should use a PreparedStatement and rarely if ever use Statement.
    2) You should start Java variable names with lower case.

  • Select distinct statement with various alias

    Hi everybody,
    I'm trying to put a select distinct statement in a query with two different alias for two different tables; like that:
    select distinct a.ma_name||'.'||a.ma_first_name d,
    a.ma_first_name||'.'||a.ma_name r
    from ma_main a, manager_liste b
    where (UPPER(b.manager_first_name||'.'||b.manager_name) = :APP_USER or
    (case when 'X'=:APP_USER or 'Y'=:APP_USER
    then 1
    else 0
    end) = 1)
    order by a.ma_name
    But it doesn't work. Can anybody help?
    Thx a lot!
    Jan

    hi,
    this is the error:
    1 error has occurred
    LOV query is invalid, a display and a return value are needed, the column names need to be different. If your query contains an in-line query, the first FROM clause in the SQL statement must not belong to the in-line query.
    and the table manager_liste and ma_main are varchar tables.
    how can i make it work, so that my select list with submit does only show distinct names. Because right now it shows each name about 10 times....

  • How do I replace 2 pantone colors with 2 new pantone colors globally? I have a 2 PMS logo with many tint variations in it . When I replace PMS in Swatches pallette. The logo does not globally replace the selected color. es

    I have a 2-PMS color logo with many tints in it of the 2 colors. When I replace the  swatches in the logo to new colors, they convert from Book Color to CMYK. Can the printer work with that? How can I kee it a 2-color separation?
    MaryFl

    This is what I understand. You have a logo in a document that uses PMS 'A' and PMS 'B' colors and you want to change to colors PMS 'C' and PMS 'D'. If this is correct there are different ways to do this, but here is a traditional way:
    Make sure Select Same Tint is turned OFF in the Preferences. And all objects are unlocked in the document.
    Get the two PMS (C and D) in the document's Swatches Panel.
    Select PMS 'A' and bring the 'Fill' box in focus.
    From the Select menu choose Same > Fill Color.
    Click on PMS 'C' in Swatches panel to replace all PMS 'A' fills with PMS 'C'.
    Deselect all.
    Again select PMS 'A' and this time bring 'Stroke' box in focus.
    From the Select menu choose Same > Stroke Color.
    Click on PMS 'C' in Swatches panel to replace all PMS 'A' strokes with PMS 'C'.
    Deselect all.
    Similarly using the same approach replace PMS 'B' wit PMS 'D'.
    If you have CS3 / CS4 and the PMS colors in the logo are easily identifiable, you can use Live Color to change the colors pretty easily.
    Hope this helps!
    - Neeraj
    New Note: If there are gradients / blends that use these PMS colors the above approach would not work, but Live Color can.

  • "connect by" problem with "select distinct"

    When I run the following SQL (using "Scott" DB):
    select *
    from emp
    where deptno = 30 or mgr is null
    start with mgr is null
    connect by prior empno = mgr
    order siblings by ename
    I get the results one would expect. The President is first and all those reporting to him/her are listed in correct sequence.
    EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
    7839,KING,PRESIDENT,,11/17/1981,5000,10
    7698,BLAKE,MANAGER,7839,5/1/1981,2850,30
    7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
    7900,JAMES,CLERK,7698,12/3/1981,950,30
    7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
    7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
    7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
    However, when I run the same query but make it "select distinct" I get the following:
    EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
    7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
    7698,BLAKE,MANAGER,7839,5/1/1981,2850,,30
    7900,JAMES,CLERK,7698,12/3/1981,950,,30
    7839,KING,PRESIDENT,,11/17/1981,5000,,10
    7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
    7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
    7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
    Why would adding "distinct" to the select cause the result to be sorted STRICTLY by ename (per "order siblings by...")?
    Finally, if I "select distinct" but don't specify any "order" I get this, in NO APPARENT order:
    EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
    7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
    7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
    7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
    7698,BLAKE,MANAGER,7839,5/1/1981,2850,,30
    7839,KING,PRESIDENT,,11/17/1981,5000,,10
    7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
    7900,JAMES,CLERK,7698,12/3/1981,950,,30
    Thanks in advance for any insight offered!
    -Gene

    you have to specify what is going to be the distict field.No you don't. DISTINCT keyword applies to the whole SELECT list. See your own link.
    In any case this does not appear to have anything to do with what you SELECT, rather that the SORT UNIQUE caused by the DISTINCT keyword appears to prevent the ORDER SIBLINGS BY clause from working correctly.
    Not really sure why you need DISTINCT in this example, no doubt this is being applied elsewhere. Given that you have duplicates in the rowset and that hierarchical query now supports views, perhaps it would be more efficient to apply DISTINCT keyword first, something like...
    SELECT e.*
    FROM (SELECT DISTINCT e.*
    FROM emp e
    WHERE e.deptno = 30
    OR e.mgr IS NULL) e
    START WITH e.mgr IS NULL
    CONNECT BY PRIOR e.empno = e.mgr
    ORDER SIBLINGS BY e.ename;
    Alternatively you could skip ORDER SIBLINGS BY clause and use SYS_CONNECT_BY_PATH function to get your order, something like...
    SELECT e.*
    FROM (SELECT DISTINCT e.*,
    SYS_CONNECT_BY_PATH () path
    FROM emp e
    WHERE e.depno = 30
    OR e.mgr IS NULL
    START WITH e.mgr IS NULL
    CONNECT BY PRIOR e.empno = e.mgr) e
    ORDER BY e.path
    Padders

  • OraException from Command.ExecuteReader with SELECT DISTINCT

    Hello
    I am trying to fill an OraDataReader object from a OraCommand object.
    It appears that whenever the statement includes a SELECT DISTINCT, the command fails (even though the SQL statement works fine when executed e.g. in TOAD)
    Dim Conn As OraConnection = New Oracle.DataAccess.Client.OraConnection("[Valid connection string]")
    Conn.Open()
    Dim Command As OraCommand = New OraCommand()
    Command.CommandType = CommandType.Text
    Command.CommandText = "select DISTINCT nvl(SUBFAMILY_COMPETENCY_ID, 0) SUBFAMILY_ID, nvl(NAME, ' ') NAME, FAMILY_COMPETENCY_ID FAMILY_ID " & _
    " from TAXONOMY_RELATIONAL, COMPETENCY " & _
    " where TAXONOMY_RELATIONAL.CL_ID = :1 " & _
    " AND COMPETENCY.cl_id (+) = TAXONOMY_RELATIONAL.cl_id and COMPETENCY.language_id (+) = :2 " & _
    " and COMPETENCY.COMPETENCY_ID (+) = TAXONOMY_RELATIONAL.SUBFAMILY_COMPETENCY_ID " & _
    " order by FAMILY_ID, SUBFAMILY_ID"
    Command.Parameters.Add("@CL_ID", context.Session!CLID)
    Command.Parameters.Add("@LANGUAGE_ID", context.Session!LANGUAGEID)
    Dim DataReader As OraDataReader = Command.ExecuteReader(CommandBehavior.CloseConnection)
    An Oracle.DataAccess.Client.OraException is raised when executing the last statement, but no further details are given in the error message. The stack trace begins as follows
    [OraException]()
    Oracle.DataAccess.Client.OraException.HandleErrorHelper(Int32 errCode, OraConnection conn, IntPtr opsErrCtx, IntPtr opsSqlCtx, Object src, String procedure) +639
    Oracle.DataAccess.Client.OraCommand.ExecuteReader(+737)
    Oracle.DataAccess.Client.OraCommand.ExecuteReader(CommandBehavior behavior) +8
    The exception disappears as soon as I remove the DISTINT keyword from my SQL statement.
    Is this a bug or am I doing something wrong?
    Thanks for help,
    Bernt Fischer

    This issue is same as the one mentioned in the thread with title "Problem with 'Select distinct'" and the fix would be available in the next release.

  • Issue with "Select Distinct" query in Oracle 10g against Oracle 9i

    Hi,
    I would appreciate if some one help me here because it is really urgent.
    We are upgrading our database from 9i to 10g.
    There are the "Select distinct" queries in the code which populated the grid on the applications screens. We found a difference in 9i and 10g the way the result is populated for these queries. If "Select Distinct" query wihtout a order by clause is executed in 9i then the result is automatically sorted. But Oracle 10g does not do this.
    We can change the queries adding order by clause but we are almost at the end of the testing and want to know if there is any way that we can do this from database settings. Would there be any impact of these settings change on overall operation of Oracle 10g?
    I would appreciate if some one can help me here.
    Thanks,
    Dinesh

    then the result is automatically sorted.No. Oracle may have done a sort operation to perform the distinct, but it still did not guarantee the order of your results.
    In 10g and in 9i, if you want your results in a certain order you must use order by.

Maybe you are looking for

  • 4th gen. Ipod Shuffle takes a long time to start playing

    When I turn on my Ipod Shuffle Gen 4, nothing happens!  Then, after a few minutes it starts to play.  I tried resetting and restoring and updating the software but nothing fixes it.  Sometimes it doesn't ever start playing - other times it is pretty

  • Possiblity of message getting lost

    I am using JCAPS 5.1.2. We have an interface where multiple calls are made at the same time to a particular JMS queue. The connection mode of the JMS queue was connection consumer mode and it frequently used to bring down the integration server. We h

  • How to make VideoRecorderBrush scollable?

    Hi. My root layout is a Grid and I'm using a Rectangle to display the AudioVideoCaptureDevice's viewfinder. I have a option to set the capture resolution to any resolution that is  available by the API. When the capture resolution is greater that the

  • Access via 'NULL'

    Hi, I am getting this error. I dont know why. Plese help. Thx in advance for your kindly efforts. Regards ertas The following error text was processed in the system I60 : Access via 'NULL' object reference not possible. The error occurred on the appl

  • ARD Login Script Problem

    Hey there. I have a Mac lab that I am controlling with ARD. I know you can use the following UNIX script to login.. osascript <<EndOfMyScript           tell application "System Events"                     keystroke "USERNAME"                     keys