Concat result of a sub-select in a single field

How can I concat all registers of a sub-select in a single field.
like:
SELECT DATE_MARK
FROM TABLE_A
WHERE COD = '123'
RESULT:
200601
200605
200607
200507
How can I put that result in a single field? like this:
'200601 200605 200607 200507'
Thanks.

In a little different approach ->
satyaki>
satyaki>select * from v$version;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
PL/SQL Release 10.2.0.3.0 - Production
CORE    10.2.0.3.0      Production
TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
Elapsed: 00:00:00.01
satyaki>
satyaki>
satyaki>drop type pipe_rec;
Type dropped.
Elapsed: 00:00:05.47
satyaki>
satyaki>
satyaki>create or replace type pipe_obj as object
  2    (
  3      dno       number(5),
  4      buff      clob
  5    );
  6  /
Type created.
Elapsed: 00:00:00.24
satyaki>
satyaki>create or replace type pipe_rec as table of pipe_obj;
  2  /
Type created.
Elapsed: 00:00:00.17
satyaki>
satyaki>
satyaki>create or replace function pivot_horizon(d_no  in number)
  2  return pipe_rec
  3  pipelined is
  4    cursor c1
  5    is
  6      select ename
  7      from emp
  8      where deptno = d_no;
  9     
10   r1 c1%rowtype;
11  
12   str clob;
13  begin
14    str:= '';
15    for r1 in c1
16    loop
17      str := str||' '||r1.ename;
18    end loop;
19      pipe row(pipe_obj(d_no,trim(str)));
20    return;
21  end;
22  /
Function created.
Elapsed: 00:00:00.18
satyaki>
satyaki>
satyaki>
satyaki>
satyaki>select *
  2  from table(cast(pivot_horizon(10) as pipe_rec));
       DNO BUFF
        10 SOURAV  CLARK KING
Elapsed: 00:00:00.11
satyaki>
satyaki>
satyaki>Regards.
Satyaki De.

Similar Messages

  • Concatenate the result of a sub select...

    OK, here's my problem. I have 2 tables, one referring to the other. Several rows from table B belong to table's A datas and I'd like to make a select where I can "concatenate" the content of table's B datas in one of my select row.
    So for, here's what I've done:
    select distinct d.code,
      c.libe "Nom",
      d.ddeb "Date de dépot",
      d.nume "Numéro de demande",
      (select p.libe from demande p where p.code=d.nume and p.natu='T' and tri=1
      ||' '
      ||
      (select p.libe from demande p where p.code=d.nume and p.natu='T' and tri=2
      ||' '
      ||
      (select p.libe from demande p where p.code=d.nume and p.natu='T' and tri=3
      ||' '
      ||
      (select p.libe from demande p where p.code=d.nume and p.natu='T' and tri=4
      ||' '
      ||
      (select p.libe from demande p where p.code=d.nume and p.natu='T' and tri=5
      ) "type",
      (select p.libe from demande p where p.code=d.nume and p.natu='C' and tri=1
      ||' '
      ||
      (select p.libe from demande p where p.code=d.nume and p.natu='C' and tri=2
      ||' '
      ||
      (select p.libe from demande p where p.code=d.nume and p.natu='C' and tri=3
      ||' '
      ||
      (select p.libe from demande p where p.code=d.nume and p.natu='C' and tri=4
      ||' '
      ||
      (select p.libe from demande p where p.code=d.nume and p.natu='C' and tri=5
      ) "Commune"
    from demandeur d,
      demande t,
      client c
    where t.code=d.nume
    and c.code  =d.code
    and c.role  ='1'
    and t.natu  ='T'
    and dfin   is null
    and ddeb    <'30/09/2008'
    and clot   is null
    and d.nume in
      (select u.code from demande u where u.libe in ('F1','F 1bis','F2','F3')
    order by d.ddeb asc ;The problem is that this methode will only display the five first rows in table B (demande). In table B, there might be between 1 and up to 14 rows for "Commune" and up to 10 rows for "Type".
    Would there be any cleaner or smarter method to do this ?
    thx

    OK, works great.
    I'm posting the modified code just for the record
    create or replace
    function getDemande(dem_nume in VARCHAR2,dem_natu in VARCHAR2) return varchar2 is
    retval varchar2(32000);
    begin
      for r in (select libe from demande where code=dem_nume and natu= dem_natu order by tri) loop
        retval := retval||r.libe||' / ';
      end loop;
      retval:=trim(trailing '/' from trim(retval));
      return retval;
    end;
    select distinct d.code,
      c.libe "Nom",
      d.ddeb "Date de dépot",
      d.nume "Numéro de demande",
      getDemande(d.nume, 'T') "Type(s)",
      getdemande(d.nume,'C') "Commune(s)"
    from demandeur d,
      demande t,
      client c
    where t.code=d.nume
    and c.code  =d.code
    and c.role  ='1'
    and dfin   is null
    and ddeb    <'30/09/2008'
    and clot   is null
    and d.nume in
      (select u.code from demande u where u.libe in ('F1','F 1bis','F2','F3')
    order by d.ddeb asc;thx all

  • Sub selects in a SQL statement

    Hi, I have a query with an obsene amount of sub selects,
    for example :
    SELECT p.ID,
    (select something from data where id = p.id) data1,
    (select somelse from data2 where id = p.id) data2,
    (select someelse from data3 where id = p.id) data3,
    (select someelse from data4 where id = p.id) data4,
    (select someelse from data5 where id = p.id) data5,
    FROM property P
    WHERE ..........
    this query is taking a long time to process. Is there a more efficient way of doing such a statement?
    thanks in advance

    Gabe:
    Since the original poster said "this query is taking a long time to process", I assumed that there was a one-to-one relationship between properties and each of the dataX tables, otherwise, as you pointed out, he would be complaining about ORA-01427: single-row subquery returns more than one row
    In my union, I am returning a single column from each of the data tables (plus the id), and a NULL for each of the other columns in the in-line view. The MAX function just gets the single row for each column that actually has a value.
    As a test case, I did:
    CREATE TABLE properties AS
    SELECT rownum id, object_name
    FROM all_objects
    WHERE rownum < 11;
    CREATE TABLE data1 (id NUMBER, descr VARCHAR2(10));
    INSERT INTO data1 VALUES(1, 'ONE');
    INSERT INTO data1 VALUES(2, 'TWO');
    INSERT INTO data1 VALUES(3, 'THREE');
    CREATE TABLE data2 (id NUMBER, descr VARCHAR2(10));
    INSERT INTO data2 VALUES(4, 'FOUR');
    INSERT INTO data2 VALUES(5, 'FIVE');
    INSERT INTO data2 VALUES(6, 'SIX');
    CREATE TABLE data3 (id NUMBER, descr VARCHAR2(10));
    INSERT INTO data3 VALUES(7, 'SEVEN');
    INSERT INTO data3 VALUES(8, 'EIGHT');
    INSERT INTO data3 VALUES(9, 'NINE');The original version as posted retrieves:
    SQL> SELECT p.id, p.object_name,
      2         (SELECT descr FROM data1 WHERE id = p.id) data1,
      3         (SELECT descr FROM data2 WHERE id = p.id) data2,
      4         (SELECT descr FROM data3 WHERE id = p.id) data3
      5  FROM properties p
      6  ORDER BY p.id;
            ID OBJECT_NAME                    DATA1      DATA2      DATA3
             1 TAB$                           ONE
             2 I_IND1                         TWO
             3 I_COBJ#                        THREE
             4 USER$                                     FOUR
             5 I_OBJ1                                    FIVE
             6 I_PROXY_ROLE_DATA$_2                      SIX
             7 BOOTSTRAP$                                           SEVEN
             8 I_ICOL1                                              EIGHT
             9 UNDO$                                                NINE
            10 PROXY_ROLE_DATA$
    10 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             93 consistent gets
              0  physical reads
              0  redo size
           1000  bytes sent via SQL*Net to client
            655  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             10  rows processedBut, it does a SELECT (hopefully indexed) of data1, data2, and data3 for each row in properties. Minimally, 9 gets per row of properties (index root, index leaf, table row for each of data1, data2, data3) without even getting any data from properties.
    My query returns:
    SQL> SELECT p.id, p.object_name, a.data1, a.data2, a.data3
      2  FROM properties p,
      3       (SELECT id, MAX(data1) data1, MAX(data2) data2, MAX(data3) data3
      4        FROM (SELECT id, descr data1, TO_CHAR(NULL) data2, TO_CHAR(NULL) data3
      5              FROM data1
      6              UNION ALL
      7              SELECT id, TO_CHAR(NULL), descr, TO_CHAR(NULL)
      8              FROM data2
      9              UNION ALL
    10              SELECT id, TO_CHAR(NULL), TO_CHAR(NULL), descr
    11              FROM data3)
    12        GROUP BY id) a
    13  WHERE p.id = a.id(+)
    14  ORDER BY p.id;
            ID OBJECT_NAME                    DATA1      DATA2      DATA3
             1 TAB$                           ONE
             2 I_IND1                         TWO
             3 I_COBJ#                        THREE
             4 USER$                                     FOUR
             5 I_OBJ1                                    FIVE
             6 I_PROXY_ROLE_DATA$_2                      SIX
             7 BOOTSTRAP$                                           SEVEN
             8 I_ICOL1                                              EIGHT
             9 UNDO$                                                NINE
            10 PROXY_ROLE_DATA$
    10 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             12 consistent gets
              0  physical reads
              0  redo size
           1000  bytes sent via SQL*Net to client
            655  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              2  sorts (memory)
              0  sorts (disk)
             10  rows processedThe same result, but 1/8 of the gets. an outer join is also possible:
    SQL> SELECT p.id, p.object_name, d1.descr data1, d2.descr data2, d3.descr data3
      2  FROM properties p, data1 d1, data2 d2, data3 d3
      3  WHERE p.id = d1.id(+) AND
      4        p.id = d2.id(+) AND
      5        p.id = d3.id(+)
      6  ORDER BY p.id;
            ID OBJECT_NAME                    DATA1      DATA2      DATA3
             1 TAB$                           ONE
             2 I_IND1                         TWO
             3 I_COBJ#                        THREE
             4 USER$                                     FOUR
             5 I_OBJ1                                    FIVE
             6 I_PROXY_ROLE_DATA$_2                      SIX
             7 BOOTSTRAP$                                           SEVEN
             8 I_ICOL1                                              EIGHT
             9 UNDO$                                                NINE
            10 PROXY_ROLE_DATA$
    10 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             12 consistent gets
              0  physical reads
              0  redo size
           1000  bytes sent via SQL*Net to client
            655  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             10  rows processedSo, the same number of gets, and it saves one sort. But if the tables are large, multiple outer joins may not be as efficient as one outer join to the union all query.
    HTH
    John

  • Sub-Select Count query breaking TOAD

    Oracle 10.2.0.4.0
    Running TOAD 9.1
    I am running some SQL on our eBusiness Suite:
    SELECT pha.segment1
         , pha.type_lookup_code
         , (SELECT COUNT(DISTINCT pha2.po_header_id)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) po_count
         , (SELECT MAX(pha2.creation_date)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) latest_cpa_po
      FROM po.po_headers_all pha
         , po.po_vendors pv
         , po.po_vendor_sites_all pvsa
    WHERE pha.vendor_id = pv.vendor_id
       AND pha.vendor_site_id = pvsa.vendor_site_id
    --   AND pv.VENDOR_NAME LIKE 'H%'
       AND pha.vendor_id = 98
       AND pha.type_lookup_code = 'CONTRACT'
       AND pha.org_id IN(7041, 7042);The above query runs quicky (approx. 1 second). If I take out the AND pha.vendor_id = 98 then the query takes a few minutes to run.
    When I try to export it, or scroll down to view > 500 rows, TOAD crashes.
    I know this isn't a TOAD forum, but I think that this is probably an issue with my no doubt rubbish SQL.
    If I take out this sub-select, then the problem doesn't happen:
         , (SELECT COUNT(DISTINCT pha2.po_header_id)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) po_countHowever, I can't work out a better way of getting the data I need.
    The sub-select counts POs which have been raised where the contractID on the PO line is the same as the PO Header ID from the main query.
    Any advice please, on what I could do to sort this out would be much appreciated.
    Thanks!

    Hi,
    It looks like you can replace both scalar sub-queries with a join, like this:
    WITH     header_lines_summary     AS
         SELECT    pla.contract_id
              ,       COUNT (DISTINCT pha2.po_header_id)     AS po_count
              ,       MAX (pha2.creation_date)          AS latest_cpa_po
              FROM        po.po_headers_all pha2
                 ,        po.po_lines_all   pla
             WHERE        pha2.po_header_id = pla.po_header_id
          GROUP BY       pla.contract_id
    )                                        -- Everything up to this line is new
    SELECT pha.segment1
         , pha.type_lookup_code
         , hls.po_count                              -- Changed
         , hls.latest_cpa_po                         -- Changed
      FROM po.po_headers_all     pha
         , po.po_vendors           pv
         , po.po_vendor_sites_all      pvsa
         , header_lines_summary     hls                    -- New
    WHERE pha.vendor_id          = pv.vendor_id
       AND pha.vendor_site_id     = pvsa.vendor_site_id
       AND pha.po_header_id          = hls.contract_id (+)          -- New
    --   AND pv.VENDOR_NAME      LIKE 'H%'
       AND pha.vendor_id           = 98
       AND pha.type_lookup_code      = 'CONTRACT'
       AND pha.org_id           IN (7041, 7042);Aside from the sub-query (which is entirely new), the query above is just what you posted, with 2 lines changed and 2 lines added, as marked.
    This should be more efficient, but I don't know for certain that it will solve the Toad problem.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
    It never hurts to say what version of Oracle you're using.

  • Speed Issue on an UPDATE from a sub-select

    Ignoring the fact this is a Spatial Query... having troubles understanding why a select finishes very quickly, yet putting the same select syntax in an UPDATE command as a sub-select takes forever to finish. Columns in the original table are indexed (ie SANITARY_MH_DATA.GIS_ID). The work-around has been to load a Temporary table with the sub-select results, followed by an UPDATE command. But it creates more sql code than needed.
    Any hints appreciated.
    Phil.
    -- FIND THE SANITARY CATCHMENT THE MANHOLE IS IN --
    -- need to add the ones that fall into more than 1 catchment
    -- with the mask=TOUCH
    UPDATE SANITARY_MH_DATA SET CATCHMENT_NAME = '';
    -- THIS BLAZES AND IS DONE IN 5 SECONDS...
    SELECT CATCHMENT_ID FROM
    (SELECT A.GIS_ID AS MANHOLE, B.GIS_ID AS CATCHMENT_ID
    FROM SANITARY_MH A, SANITARY_CATCHMENT B
    WHERE SDO_RELATE (A.GEOMETRY,B.GEOMETRY, 'mask=INSIDE querytype=Window') = 'TRUE');
    -- THIS BOGS DOWN AND TAKES FOREVER TO FINISH...
    UPDATE SANITARY_MH_DATA SET CATCHMENT_NAME = ( SELECT CATCHMENT_ID FROM
    (SELECT A.GIS_ID AS MANHOLE, B.GIS_ID AS CATCHMENT_ID
    FROM SANITARY_MH A, SANITARY_CATCHMENT B
    WHERE SDO_RELATE (A.GEOMETRY,B.GEOMETRY, 'mask=INSIDE querytype=Window') = 'TRUE')
    WHERE SANITARY_MH_DATA.GIS_ID = A.MANHOLE);
    EXIT;
    Edited by: user13174287 on 24-Aug-2010 3:51 PM
    Edited by: user13174287 on 24-Aug-2010 4:06 PM

    There is such a way, however I doubt that it will work in your case. There are some restrictions on it.
    You can write an update to a kind of inline query.
    UPDATE (select dat.*, mh.GIS_ID AS MANHOLE, cat.GIS_ID CATCHMENT_ID
           from SANITARY_MH_DATA dat,  SANITARY_MH mh, SANITARY_CATCHMENT cat
           where SDO_RELATE (mh.GEOMETRY,cat.GEOMETRY, 'mask=INSIDE querytype=Window') = 'TRUE'
           and dat.GIS_ID = mh.GIS_ID
           ) v
    SET v.CATCHMENT_NAME = v.CATCHMENT_ID
    WHERE (v.CATCHMENT_NAME != v.CATCHMENT_ID or v.CATCHMENT_NAME is null)
    ;there is some join criteria missing between cat and dat. MAybe it would work if the CATACHMENT ID is fetched in the selct clause of the inline view, instead of joining it.
    UPDATE (select dat.*, mh.GIS_ID AS MANHOLE,
                        (select cat.GIS_ID from SANITARY_CATCHMENT cat
                         where SDO_RELATE (mh.GEOMETRY,cat.GEOMETRY, 'mask=INSIDE querytype=Window') = 'TRUE'
                         and rownum = 1) as catchment_id
           from SANITARY_MH_DATA dat,  SANITARY_MH mh
           where dat.GIS_ID = mh.GIS_ID
           ) v
    SET v.CATCHMENT_NAME = v.CATCHMENT_ID
    WHERE (v.CATCHMENT_NAME != v.CATCHMENT_ID or v.CATCHMENT_NAME is null)
    ;Oh and there is the MERGE statement. This might help in your case.
    Edited by: Sven W. on Aug 25, 2010 9:19 PM

  • Is `WHERE` clause pointless inside a sub-select?

    WHERE is part of the definition of a sub-select:
    [WITH [<calc-clause> ...]]
    SELECT [<axis-spec> [, <axis-spec> ...]]
    FROM [<identifier> | (< sub-select-statement >)]
    [WHERE <slicer>]
    [[CELL] PROPERTIES <cellprop> [, <cellprop> ...]]
    < sub-select-statement > :=
    SELECT [<axis-spec> [, <axis-spec> ...]]
    FROM [<identifier> | (< sub-select-statement >)]
    [WHERE <slicer>]I understand that a subselect does not reduce dimensionality or set context.
    If overall context of a script is not driven via a sub-select then is there ever a point in using this WHERE clause in the subselect? 
    An example in Adventure Works:
    SELECT
    [Measures].[Order Count] ON 0
    [Geography].[Country] * [Product].[Category] ON 1
    FROM
    SELECT
    [Geography].[Country].[Australia] ON 0
    FROM [Adventure Works]
    WHERE
    [Product].[Category].[Bikes]

    Hi WhyTheQ,
    According to your description, you want to know if the Where clause is working when the main select statement is not driven via the sub-select. Right?
    In MDX, Where clause is used for defining slicer axis so that only the data intersecting the with the specified member will be returned. It will work in the sub-select to restrict the data. However, the return result from sub-select should match
    the set on your axis. In this scenario, your sub-select returns an aggregation value of a dimension member, but in your main select row level expects a tuple set. So your can't get the result and it will throw error.
    Reference:
    Specifying the Contents of a Slicer Axis (MDX)
    Best Regards,
    Simon Hou
    TechNet Community Support

  • Aggregate Sub-Selects

    OK, this is probably only for the more advanced.
    I have a query that gives me an (ORA-000979) Not a Group By Expression whenever I have a sub-select in the select clause that has an aggregate function.
    For Example, the following:
    SELECT
    Items.A,
    SUM(Items.B * Items.C) As D,
    Inventory.A,
    Warehouses.A,
    (SELECT
    Sum(InventoryAudit.Qty)
    FROM
    InventoryAudit
    WHERE
    InventoryAudit.Item_ID =
    InventoryMain.Item_ID)
    FROM
    Inventory,
    Items,
    Warehouses
    WHERE
    ITEMS.A = 4
    AND Warehouses.A = Items.D
    Group By
    Items.A,
    Inventory.A,
    Warehouses.A
    null

    Braden,
    As moonriver pointed out, you are missing the InventoryMain table in your from clause in your inner sub-query.
    You also don't have enough join conditions in your outer query. You have three tables in your outermost from clause: inventory, items, and warehouses. Bearing in mind that the minimum number of join conditions required to join n tables is n-1, then to join 3 tables, you need at least 2 join conditions, but you only have 1 join condition. Every table in the from clause must be joined, but you haven't provided a join condition for the inventory table. You need to join the inventory table to either the items table or the warehouses table.
    In the code below, I have placed two dashes -- in front of each line that I added where your code was missing a line. This is just a start. There may be other errors. It would help to have the structure of your tables and an explanation and example of the results you are trying to achieve.
    SELECT Items.A,
    SUM (Items.B * Items.C) As D,
    Inventory.A,
    Warehouses.A,
    (SELECT SUM (InventoryAudit.Qty)
    FROM InventoryAudit
    -- , InventoryMain
    WHERE InventoryAudit.Item_ID = InventoryMain.Item_ID)
    FROM Inventory,
    Items,
    Warehouses
    WHERE ITEMS.A = 4
    AND Warehouses.A = Items.D
    -- AND Inventory.? = ?.?
    GROUP BY Items.A,
    Inventory.A,
    Warehouses.A;Barbara
    null

  • Sub select query Help

    I have to do a task of finding records which matches the following logic.
    My table has PID varchar(15), Amount varchar (50),Status varchar(20) columns.
    Each PID can go thru changes in a period of time, in my case i dont have a data range I just have a flatfile which consists of three types of PID`s
    123456 = Original_PID, Reversal =123456R1,Adjustment= 123456A1.
    Basically What I am trying to find out if there are any original PID`s which has a Reversal or an Adjustment.
    here`s the code I have started on... Can someone help me get it finished?
    select R1. pid,a1.pid,org.pid from (
    select SUBSTRING(Pid,1,11)as Original_PID, status, paid_amount as Amount from dbo.Q2STATUS)org
    inner join (select SUBSTRING(Pid,1,13)as Original_Icn,status,paid_amount from dbo.Q2STATUS
    where SUBSTRING(Pid,12,2) ='R1')r1 on r1.pid=org.pid
    inner join (select SUBSTRING(claim_id,1,13)as Original_Icn,status,paid_amount from dbo.Q2STATUS
    where SUBSTRING(Pid,12,2) ='A1')A1 on a1.Pid=org.PID
    FM

    Hi,
    Please check following item
    It uses a
    SQL string function, please create it first
    create table Q2STATUS (Pid nvarchar(200), Status varchar(20), paid_amount int)
    insert into Q2STATUS select '123456 = Original_PID, Reversal =123456R1, Adjustment= 123456A1',NULL,250
    with cte2 as (
    select rn = row_number() over (order by pid), * from Q2STATUS
    ), cte as (
    select cte2.*, s.id typeid, v.*
    from cte2
    cross apply dbo.split(cte2.Pid, ',') s
    cross apply dbo.split(s.val, '=') v
    ), cte3 as (
    select
    rn, pid, status, paid_amount, max(pidtype) pidtype, max(pidval) pidval
    from (
    select
    rn, Pid, status, paid_amount, typeid,
    case when (typeid = 1 and id = 2) or (typeid <> 1 and id = 1) then ltrim(rtrim(val)) else null end as pidtype,
    case when (typeid = 1 and id = 1) or (typeid <> 1 and id = 2) then ltrim(rtrim(val)) else null end as pidval
    from cte
    ) g
    group by rn, pid, status, paid_amount, typeid
    select
    cte2.rn, cte2.pid,
    cte3.pidval as 'Original_PID',
    cte4.pidval as 'Reversal',
    cte5.pidval as 'Adjustment'
    from cte2
    left join cte3 on cte3.rn = cte2.rn and pidtype = 'Original_PID'
    left join cte3 as cte4 on cte4.rn = cte2.rn and cte4.pidtype = 'Reversal'
    left join cte3 as cte5 on cte5.rn = cte2.rn and cte5.pidtype = 'Adjustment'
    Here is the result,
    Please note that I have used
    SQL CTE expressions a lot in the SQL query to prevent usage of sub-select and temp tables.
    There is also a
    SQL ROW_NUMBER() function used in the first SELECT statement to distinquish all items from each other instead of using the PID column value. Perhaps you have already an ID key column, you can use it too
    SQL Server, SQL Server 2012 Denali and T-SQL Tutorials

  • Select on MARA resulting into # values in internal table for one field

    Hi Team,
    I have written a SELECT statement on MARA table as below.
    TRY.
            SELECT matnr zzwftag FROM mara CLIENT SPECIFIED
              INTO CORRESPONDING FIELDS OF TABLE gt_mara WHERE
              mandt = sy-mandt AND
              zzwftag NE space
              AND zzwftag IS NOT NULL
              AND zzwftag NE '#'
              AND zzwftag NE '%#%'
              AND zzwftag NE '  '
              AND zzwftag NOT LIKE '%/%'(012).
          CATCH cx_sy_dynamic_osql_error.
            MESSAGE 'Error While Fetching Data from MARA'(044) TYPE 'S'(040)  DISPLAY LIKE 'W'(041).
        ENDTRY.
        IF NOT gt_mara[] IS INITIAL.
          DELETE gt_mara[] WHERE zzwftag EQ '#'
          OR zzwftag IS INITIAL
          OR zzwftag EQ space
          OR zzwftag EQ ' '.
        ENDIF.
    Observations: 1. In
    the resulting internal table I am seeing '#' values for fields zzwftag which are actually empty when I see the record in SE11 in MARA(ALV display). It shows '#' in it in SE16 display(We can choose User parameters and hence mode of display in SE11)
    The requirement is to avoid those records where zzwftag is initial i.e. blank. I tried to delete invalid records but to no avail.
    Please suggest any way where I can get the Select correct.
    Regards,
    Amit

    Please do not use so many not conditions in one query....
    Using so many negative conditions results in bad data.
    Instead use delete statements later this would not confuse the system.
    Also if you are using sy-mandt then i think you should not use client specified system will take care of it.
    TRY.
    SELECT matnr zzwftag FROM mara CLIENT SPECIFIED
    INTO CORRESPONDING FIELDS OF TABLE gt_mara WHERE
    mandt = sy-mandt AND
    zzwftag NE space.
    CATCH cx_sy_dynamic_osql_error.
    MESSAGE 'Error While Fetching Data from MARA'(044) TYPE 'S'(040) DISPLAY LIKE 'W'(041).
    ENDTRY.
    IF NOT gt_mara[] IS INITIAL.
    DELETE gt_mara[] WHERE zzwftag EQ '#'
    OR zzwftag IS INITIAL
    OR zzwftag EQ space
    OR zzwftag EQ ' '.
    delete gt_mara[] where zzwflag eq '%#%'.
    ENDIF.

  • How to add a dummy row in the result set of a SELECT statement.

    Hello Everyone -
    I have requirment to add a dummy row in the result set of a SELECT statement.
    For e.g. lets say there is a table Payment having following colums:
    Payment_id number
    status varchar2(10)
    amount number
    payment_date date
    so here is the data :-
    Payment_id Status Amount payment_date
    1 Applied 100 12/07/2008
    2 Reversed 200 01/ 06/2009
    3 Applied 300 01/ 07/2009
    Here is my SQL
    Select * form payment where payment_date >= 01/01/2009
    Output will be
    2 Reversed 200 01/ 06/2009
    3 Applied 300 01/ 07/2009
    My desired output is below
    2 Reversed 200 01/ 06/2009
    3 Applied 300 01/ 07/2009
    2 Reversed -200 01/ 06/2009 ------(Dummy Row)
    Thrid row here is the dummy row which I want to add when status is "Reversed"
    I would be very thankful for any kind of help in this regard ...
    Thanks,
    Gaurav

    Cartesion joining against a dummy table is a useful method of creating a dummy row:
    with my_tab as (select 1 cust_id, 1 Payment_id, 'Applied' Status, 100 Amount, to_date('12/07/2008', 'mm/dd/yyyy') payment_date from dual union all
                    select 1 cust_id, 2 Payment_id, 'Reversed' Status, 200 Amount, to_date('01/06/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 1 cust_id, 3 Payment_id, 'Applied' Status, 300 Amount, to_date('01/06/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 1 Payment_id, 'Applied' Status, 100 Amount, to_date('12/07/2008', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 2 Payment_id, 'Reversed' Status, 200 Amount, to_date('01/05/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 3 Payment_id, 'Applied' Status, 300 Amount, to_date('01/06/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 4 Payment_id, 'Reversed' Status, -400 Amount, to_date('01/06/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 5 Payment_id, 'Applied' Status, 500 Amount, to_date('01/07/2009', 'mm/dd/yyyy') payment_date from dual),
                    --- end of mimicking your table
          dummy as (select 'Reversed' col1, 1 rn from dual union all
                    select 'Reversed' col1, 2 rn from dual)
    select mt.cust_id,
           mt.payment_id,
           mt.status,
           decode(dummy.rn, 2, -1*mt.amount, mt.amount) amount,
           mt.payment_date
    from   my_tab mt,
           dummy
    where  mt.status = dummy.col1 (+)
    order by mt.cust_id, mt.payment_id, dummy.rn nulls first;
    CUST_ID     PAYMENT_ID     STATUS     AMOUNT     PAYMENT_DATE
    1     1     Applied     100     07/12/2008
    1     2     Reversed     200     06/01/2009
    1     2     Reversed     -200     06/01/2009
    1     3     Applied     300     06/01/2009
    2     1     Applied     100     07/12/2008
    2     2     Reversed     200     05/01/2009
    2     2     Reversed     -200     05/01/2009
    2     3     Applied     300     06/01/2009
    2     4     Reversed     -400     06/01/2009
    2     4     Reversed     400     06/01/2009
    2     5     Applied     500     07/01/2009Edited by: Boneist on 07-Jan-2009 23:10
    NB. You may have to mess around with the ordering if that's not come back in the order you wanted. You didn't mention what the rules were for any expected ordering though, so I've made up my own *{;-)
    Also, I added an identifier (cust_id) to differentiate between different sets of payments, since that's usually the case. Remove that if it's not applicable for your case.

  • Sub-Select SQL query in Oracle BI Answers

    Hi
    What's the proper usage of Sub-Select SQL query in Oracle BI Answers Version Oracle Business Intelligence 10.1.3.2.1?
    I get [SQL_STATE: HY000] [nQSError: 10058] A general error has occured when trying to Sub Select query like:
    itemno = (SELECT MIN(orders.itemno) FROM mydatabase where rownum < 2 order by orders.itemno)

    Maybe the best is to create a new physical and logical object for your sub-select and join this with your current objects.

  • Delete statement that uses a sub-select with the statement in the cursor

    Hi all,
    How to write write a delete statement that uses a sub-select with the statement in the cursor?
    CURSOR excluded_dates IS         
           SELECT TO_TIMESTAMP(report_parameter_value, in_date_format_mask)
          INTO my_current_date_time
          FROM report_parameters
         WHERE report_parameters.report_parameter_id    = in_report_parameter_id
           AND report_parameters.report_parameter_group = 'DATE_TIME'
           AND report_parameters.report_parameter_name  = 'EXCLUDED_DATE';
    OPEN excluded_dates;
      LOOP
        FETCH excluded_dates INTO my_excluded_date;
        EXIT WHEN excluded_dates%NOTFOUND;
        DELETE FROM edr_rpt_tmp_inclusion_table
        WHERE TO_CHAR(date_time, 'mm/dd/yyyy') = TO_CHAR(my_excluded_date, 'mm/dd/yyyy');
      END LOOP;
      CLOSE excluded_dates;Thanks

    Hi,
    In such case I think is better to create a view an perform the delete using it. Example (using HR schema):
    Connected to Oracle Database 10g Express Edition Release 10.2.0.1.0
    Connected as hr
    SQL> create or replace view v_employees as select * from employees where first_name like 'J%';
    View created
    SQL> select * from v_employees;
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE   JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID
            110 John                 Chen                      JCHEN                     515.124.4269         28/09/1997  FI_ACCOUNT    8200,00                       108           100
            112 Jose Manuel          Urman                     JMURMAN                   515.124.4469         07/03/1998  FI_ACCOUNT    7800,00                       108           100
            125 Julia                Nayer                     JNAYER                    650.124.1214         16/07/1997  ST_CLERK      3200,00                       120            50
            127 James                Landry                    JLANDRY                   650.124.1334         14/01/1999  ST_CLERK      2400,00                       120            50
            131 James                Marlow                    JAMRLOW                   650.124.7234         16/02/1997  ST_CLERK      2500,00                       121            50
            133 Jason                Mallin                    JMALLIN                   650.127.1934         14/06/1996  ST_CLERK      3300,00                       122            50
            139 John                 Seo                       JSEO                      650.121.2019         12/02/1998  ST_CLERK      2700,00                       123            50
            140 Joshua               Patel                     JPATEL                    650.121.1834         06/04/1998  ST_CLERK      2500,00                       123            50
            145 John                 Russell                   JRUSSEL                   011.44.1344.429268   01/10/1996  SA_MAN       14000,00           0,40        100            80
            156 Janette              King                      JKING                     011.44.1345.429268   30/01/1996  SA_REP       10000,00           0,35        146            80
            176 Jonathon             Taylor                    JTAYLOR                   011.44.1644.429265   24/03/1998  SA_REP        8600,00           0,20        149            80
            177 Jack                 Livingston                JLIVINGS                  011.44.1644.429264   23/04/1998  SA_REP        8400,00           0,20        149            80
            181 Jean                 Fleaur                    JFLEAUR                   650.507.9877         23/02/1998  SH_CLERK      3100,00                       120            50
            186 Julia                Dellinger                 JDELLING                  650.509.3876         24/06/1998  SH_CLERK      3400,00                       121            50
            189 Jennifer             Dilly                     JDILLY                    650.505.2876         13/08/1997  SH_CLERK      3600,00                       122            50
            200 Jennifer             Whalen                    JWHALEN                   515.123.4444         17/09/1987  AD_ASST       4400,00                       101            10
    16 rows selected
    SQL> delete from v_employees where hire_date >= to_date('01/06/1998', 'dd/mm/yyyy');
    2 rows deleted
    SQL> regards,

  • How to return the result set of multiple select statements as one result set?

    Hi All,
    I have multiple select statements in my stored procedure that I want to return as one result set 
    for instance 
    select id from tableA
    union 
    select name from table b 
    but union will not work because the result sets datatypes are not identical so how to go about this ?
    Thanks

    You have to CAST or CONVERT (or implicitly convert) the columns to the same datatype.  You must find a datatype that both columns can be converted to without error.  In your example I'm guessing id is an int and name is a varchar or nvarchar. 
    Since you didn't convert the datatypes, SQL will use its data precedence rules and attempt to convert name to an int.  If any row contains a row that has a value in name that cannot be converted to an int, you will get an error.  The solution is
    to force SQL to convert the int to varchar.  So you want something like
    select cast(id as varchar(12)) from tableA
    union
    select name from tableb
    If the datatypes are something other that int or varchar, you must find a compatable datatype and then convert one (or both) of the columns to that datatype.
    Tom

  • Using an Aggregate Function in a Sub-SELECT

    Ok. I have this Sub-SELECT and I'd like to base my outside query based on the resyult set of my inner Sub-SELECT which contains an Aggregate function.
    Is that possible???
    Here's the Query...
    SELECT *
    FROM CUSTPRO.CPM_PND_TRAN_HDR CPMPNDTH
    INNER JOIN (SELECT CPMPNDT2.ky_pnd_seq_trans,
    CPMPNDT2.id_ba_esco,
    CPMPNDT2.ky_ba,
    CPMPNDT2.ky_enroll,
    MAX(CPMPNDT2.dt_billed_by_css)
    FROM CUSTPRO.CPM_PND_TRAN_HDR CPMPNDT2
    WHERE CPMPNDT2.ky_pnd_seq_trans IN (6544937)
    GROUP BY CPMPNDT2.ky_pnd_seq_trans,
    CPMPNDT2.id_ba_esco,
    CPMPNDT2.ky_ba,
    CPMPNDT2.ky_enroll) DERIVE1
    ON CPMPNDTH.id_ba_esco = DERIVE1.id_ba_esco
    AND CPMPNDTH.ky_ba = DERIVE1.ky_ba
    AND CPMPNDTH.ky_enroll = DERIVE1.ky_enroll
    AND CPMPNDTH.dt_billed_by_css = ????DERIVE1.MAX(CPMPNDT2.dt_billed_by_css)???
    How can I designate that last qualifier ????....
    PSULionRP

    You should give your aggregate function a column-alias as in:
    SELECT *
    FROM   custpro.cpm_pnd_tran_hdr cpmpndth
           INNER JOIN (SELECT   cpmpndt2.ky_pnd_seq_trans,
                                cpmpndt2.id_ba_esco,
                                cpmpndt2.ky_ba,
                                cpmpndt2.ky_enroll,
                                Max(cpmpndt2.dt_billed_by_css) as XXX    -- ADDED THIS.
                       FROM     custpro.cpm_pnd_tran_hdr cpmpndt2
                       WHERE    cpmpndt2.ky_pnd_seq_trans IN (6544937)
                       GROUP BY cpmpndt2.ky_pnd_seq_trans,
                                cpmpndt2.id_ba_esco,
                                cpmpndt2.ky_ba,
                                cpmpndt2.ky_enroll) derive1
             ON cpmpndth.id_ba_esco = derive1.id_ba_esco
                AND cpmpndth.ky_ba = derive1.ky_ba
                AND cpmpndth.ky_enroll = derive1.ky_enroll
                AND cpmpndth.dt_billed_by_css = derive1.XXX
    /

  • A very slow select with sub selects sql statement on Oracle

    Hi,
    I'm moving an application from MySql to Oracle. The following select were very efficiently executed in MySql. In oracle its slow like a snail.
    Do anyone have a hint on how to speed it up?
    The slow part is the four sub selects in the select part. Removing them makes the select about 50 times faster on Oracle.
    Best Regards,
    Stephane
    select
    (select count(*) from relation rr where rr.document_id = d.id and rr.product_id = ? and (rr.relation_type_id = 'link' OR rr.relation_type_id = 'product')) as relationList,
    (select count(*) from relation rr where rr.document_id = d.id and rr.product_id = ? and rr.relation_type_id = 'number') as relationNumber,
    (select count(*) from relation rr where rr.document_id = d.id and rr.product_id = ? and rr.relation_type_id = 'title') as relationTitle,
    (select count(*) from relation rr where rr.document_id = d.id and rr.product_id = ? and rr.relation_type_id = 'content') as relationText,
    d.*
    from document d,(
    select distinct r.document_id id
    from relation r
    where
    r.product_id = ?
    ) dd
    where d.id=dd.id

    You are accessing the relation-table too many times, so a rewrite to a query like this
    SQL> select dept.deptno
      2       , dept.dname
      3       , count(decode(job,'CLERK',1)) clerk
      4       , count(decode(job,'MANAGER',1)) manager
      5       , count(decode(job,'SALESMAN',1)) salesman
      6    from dept, emp
      7   where dept.deptno = emp.deptno (+)
      8   group by dept.deptno
      9       , dept.dname
    10  /
        DEPTNO DNAME               CLERK    MANAGER   SALESMAN
            10 ACCOUNTING              1          1          0
            20 RESEARCH                2          1          0
            30 SALES                   1          1          4
            40 OPERATIONS              0          0          0
    4 rijen zijn geselecteerd.will be worth the effort.
    If still not satisfied, you have to do some investigation, as described [url http://forums.oracle.com/forums/thread.jspa?threadID=501834&tstart=0]here
    Regards,
    Rob.

Maybe you are looking for