Aggregate sql select

Hi,
I'm in Oracle 11g, need some help writing aggregate sql select. That might be really easy I hope.
We are doing some web analytics and counting clicks on a company’s web site, so I have to count sums on clicks, visitors and sessions from activity table.
t_agg_activity( date_key, site_id, segment_id, page_id, visitor_count, views_count, session_count)
The problem is with the Totals numbers. There are visitors and their segments. Segments are also divided by groups. So I need to count records and distinct visitors and distinct sessions.
Also I need three  records  for Totals: total all and total in group 1 and total in group 2 with the segment key -1, -2, -3 respectively. No Totals for group 3 needed.
Not sure how to deal with those totals. Should I use Roll Up function or analytic SUM function may be?
create table t_sites(site_id  NUMBER, site_code VARCHAR2(50));
insert into t_sites(site_id  , site_code )
values( 1, 'site_1');
insert into t_sites(site_id  , site_code )
values( 2, 'site_2');
insert into t_sites(site_id  , site_code )
values( 3, 'site_3');
create table t_segments(segment_id  NUMBER, segment_group VARCHAR2(50), segment_code VARCHAR2(50));
insert into t_segments(segment_id  , segment_group , segment_code )
values(1, 'seg_group_1', 'AAA');
insert into t_segments(segment_id  , segment_group , segment_code )
values(2, 'seg_group_1', 'BBB');
insert into t_segments(segment_id  , segment_group , segment_code )
values(3, 'seg_group_1', 'CCC');
insert into t_segments(segment_id  , segment_group , segment_code )
values(4, 'seg_group_2', 'DDD');
insert into t_segments(segment_id  , segment_group , segment_code )
values(5, 'seg_group_2', 'EEE');
insert into t_segments(segment_id  , segment_group , segment_code )
values(6, 'seg_group_2', 'FFF');
insert into t_segments(segment_id  , segment_group , segment_code )
values(7, 'seg_group_3', 'GGG');
insert into t_segments(segment_id  , segment_group , segment_code )
values(8, 'seg_group_3', 'HHH');
insert into t_segments(segment_id  , segment_group , segment_code )
values(9, 'seg_group_3', 'III');
insert into t_segments(segment_id  , segment_group , segment_code )
values(-1, 'Total All', 'Total');
insert into t_segments(segment_id  , segment_group , segment_code )
values(-2, 'Total seg_group_1', 'Total G1');
insert into t_segments(segment_id  , segment_group , segment_code )
values(-3, 'Total seg_group_2', 'Total G2');
create table t_activity( date_key NUMBER, page_id NUMBER, site_id  NUMBER, segment_id NUMBER, visitor_id NUMBER, session_id NUMBER);
insert into t_activity( date_key, page_id, site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 1, 1, 1);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 1, 1, 1);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 1, 1, 2);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 1, 2, 2);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 1, 2, 2);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 1, 2, 22);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 4, 2, 10);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 4, 2, 10);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 4, 2, 10);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 7, 3, 100);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 7, 3, 100);
insert into t_activity( date_key, page_id,site_id, segment_id, visitor_id, session_id)
values( 2456141, 1, 1, 7,  3, 100);
create table t_agg_activity( date_key NUMBER, site_id NUMBER, segment_id NUMBER,  page_id NUMBER, visitor_count NUMBER, views_count NUMBER, session_count NUMBER)
Edited by: 955537 on Aug 28, 2012 11:19 AM

955537 wrote:
If you can help with the full query?
with t as (
           select  nvl2(segment_group,'Total ' || segment_group,'Total All') segment_group,
                   count(*) cnt
             from  t_activity a,
                   t_segments s
             where s.segment_id = a.segment_id
             group by rollup(segment_group)
select  segment_id,
         count(*)
  from   t_activity
  group by segment_id
union all
select  segment_id,
         cnt
   from  t,
         t_segments s
   where s.segment_group = t.segment_group
SEGMENT_ID   COUNT(*)
         1          6
         4          3
         7          3
        -1         12
        -2          6
        -3          3
6 rows selected.
SQL>  SY.

Similar Messages

  • Dynamic SQL select parameters

    Until runtime I don't know the table name and column-name on which I have to do a select.
    Here is my SQL:
          SELECT single <b>w_sum_col_name </b> FROM (w_tbl_name)
            INTO ZOH_AUDIT-ZOH_NET1
           WHERE REQUID = ZOH_AUDIT-REQUID.
    My SQL fails when I have SUM(any_column) in the string w_sum_col_name. However it works if its a just a column name of the table. Failure is when the w_sum_col_name string has an aggregate function.
    Error is ..SAPSQL_ILLEGAL_AGGREGATE" CX_SY_DYNAMIC_OSQL_SYNTAX
    Any alternatives for my requirement is appreciated.

    Try this code.
    REPORT zreport NO STANDARD PAGE HEADING MESSAGE-ID zfi
                                            LINE-COUNT 65
                                            LINE-SIZE 120.
    PARAMETERS: p_matnr LIKE mara-matnr.
    DATA: mytable      LIKE dd02l-tabname,
          fields(50)   TYPE c OCCURS 0 WITH HEADER LINE,
          labst        LIKE mard-labst.
    TABLES: mard.
    DEFINE select_statement.
      select (&1) into &2
                  from (&3)
                 where matnr = p_matnr.
      endselect.
    END-OF-DEFINITION.
    fields = 'SUM( LABST )'.
    APPEND fields.
    mytable = 'MARD'.
    select_statement fields[] labst 'MARD'.
    WRITE:/ labst.

  • Oracle SQL Select query takes long time than expected.

    Hi,
    I am facing a problem in SQL select query statement. There is a long time taken in select query from the Database.
    The query is as follows.
    select /*+rule */ f1.id,f1.fdn,p1.attr_name,p1.attr_value from fdnmappingtable f1,parametertable p1 where p1.id = f1.id and ((f1.object_type ='ne_sub_type.780' )) and ( (f1.id in(select id from fdnmappingtable where fdn like '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#%')))order by f1.id asc
    This query is taking more than 4 seconds to get the results in a system where the DB is running for more than 1 month.
    The same query is taking very few milliseconds (50-100ms) in a system where the DB is freshly installed and the data in the tables are same in both the systems.
    Kindly advice what is going wrong??
    Regards,
    Purushotham

    SQL> @/alcatel/omc1/data/query.sql
    2 ;
    9 rows selected.
    Execution Plan
    Plan hash value: 3745571015
    | Id | Operation | Name |
    | 0 | SELECT STATEMENT | |
    | 1 | SORT ORDER BY | |
    | 2 | NESTED LOOPS | |
    | 3 | NESTED LOOPS | |
    | 4 | TABLE ACCESS FULL | PARAMETERTABLE |
    |* 5 | TABLE ACCESS BY INDEX ROWID| FDNMAPPINGTABLE |
    |* 6 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
    |* 7 | TABLE ACCESS BY INDEX ROWID | FDNMAPPINGTABLE |
    |* 8 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
    Predicate Information (identified by operation id):
    5 - filter("F1"."OBJECT_TYPE"='ne_sub_type.780')
    6 - access("P1"."ID"="F1"."ID")
    7 - filter("FDN" LIKE '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#
    8 - access("F1"."ID"="ID")
    Note
    - rule based optimizer used (consider using cbo)
    Statistics
    0 recursive calls
    0 db block gets
    0 consistent gets
    0 physical reads
    0 redo size
    0 bytes sent via SQL*Net to client
    0 bytes received via SQL*Net from client
    0 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    9 rows processed
    SQL>

  • How many columns a sql selects

    I need to find out how many columns are in a sql statement like below:
    sql = "select id, decode(description,'','No decription', description), comment from my_table";
    The sql string is build dynamically so I don't know it when I write the code. I need to know before I do
    call rs.next(), because I need to set up the table header so I need to know how many columns the sql is selecting.
    Thanks inadvance.
    Botao

    You can use the interface ResultSetMetaData,below are some methods of it.
    int getColumnCount()
    Returns the number of columns in this ResultSet object.
    String getColumnName(int column)
    Get the designated column's name.
    int getColumnType(int column)
    Retrieves the designated column's SQL type.
    for more infomation ,you can refer to JDBC Online Document.

  • Sql select query problem

    hi friends,
    i've a view called "risk_efforts" with fields user_id,user_name,wknd_dt,week_day,prod_efforts,unprod_efforts.
    Name Type
    ROW_ID NUMBER
    USER_ID VARCHAR2(14)
    USER_NAME VARCHAR2(50)
    WKND_DT VARCHAR2(8)
    WEEK_DAY VARCHAR2(250)
    PROD_EFFORTS NUMBER
    UNPROD_EFFORTS NUMBER
    data is like this:
    when there is some data in prod_efforts, unprod_efforts will be null
    when there is some data in unprod_efforts, prod_efforts will be null
    for example:
    USER_ID     USER_NAME     WKND_DT     WEEK_DAY     PROD_EFFORTS     UNPROD_EFFORTS
    G666999     GTest     20100403     TUE     null 3
    G666999     GTest     20100403     TUE     14     null
    now i want to combine these 2 rows into 1 row i.e o/p should be like this
    USER_ID     USER_NAME     WKND_DT     WEEK_DAY     PROD_EFFORTS     UNPROD_EFFORTS
    G666999     GTest     20100403     TUE     14 3
    i've tried all combinations but couldn't get the query. Please help me with the exact SQL select query.
    thanks,
    Girish

    Welcome to the forum.
    First read this:
    Urgency in online postings
    Secondly, it's always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
    You have provided #3 and #4. However with no usable form of sample data forum members will often not respond as quickly as they could if you provided #2.
    I'm just wagering a guess here but what about this:SELECT ROW_ID
    , USER_ID
    , WKND_DT
    , WEEK_DAY
    , MAX(PROD_EFFORTS) AS PROD_EFFORTS
    , MAX(UNPROD_EFFORTS) AS UNPROD_EFFORTS
    FROM RISK_EFFORTS
    GROUP BY ROW_ID
    , USER_ID
    , WKND_DT
    , WEEK_DAY                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Need help for SQL SELECT query to fetch XML records from Oracle tables having CLOB field

    Hello,
    I have a scenario wherein i need to fetch records from several oracle tables having CLOB fields(which is holding XML) and then merge them logically to form a hierarchy XML. All these tables are related with PK-FK relationship. This XML hierarchy is having 'OP' as top-most root node and ‘DE’ as it’s bottom-most node with One-To-Many relationship. Hence, Each OP can have multiple GM, Each GM can have multiple DM and so on.
    Table structures are mentioned below:
    OP:
    Name                             Null                    Type        
    OP_NBR                    NOT NULL      NUMBER(4)    (Primary Key)
    OP_DESC                                        VARCHAR2(50)
    OP_PAYLOD_XML                           CLOB       
    GM:
    Name                          Null                   Type        
    GM_NBR                  NOT NULL       NUMBER(4)    (Primary Key)
    GM_DESC                                       VARCHAR2(40)
    OP_NBR               NOT NULL          NUMBER(4)    (Foreign Key)
    GM_PAYLOD_XML                          CLOB   
    DM:
    Name                          Null                    Type        
    DM_NBR                  NOT NULL         NUMBER(4)    (Primary Key)
    DM_DESC                                         VARCHAR2(40)
    GM_NBR                  NOT NULL         NUMBER(4)    (Foreign Key)
    DM_PAYLOD_XML                            CLOB       
    DE:
    Name                          Null                    Type        
    DE_NBR                     NOT NULL           NUMBER(4)    (Primary Key)
    DE_DESC                   NOT NULL           VARCHAR2(40)
    DM_NBR                    NOT NULL           NUMBER(4)    (Foreign Key)
    DE_PAYLOD_XML                                CLOB    
    +++++++++++++++++++++++++++++++++++++++++++++++++++++
    SELECT
    j.op_nbr||'||'||j.op_desc||'||'||j.op_paylod_xml AS op_paylod_xml,
    i.gm_nbr||'||'||i.gm_desc||'||'||i.gm_paylod_xml AS gm_paylod_xml,
    h.dm_nbr||'||'||h.dm_desc||'||'||h.dm_paylod_xml AS dm_paylod_xml,
    g.de_nbr||'||'||g.de_desc||'||'||g.de_paylod_xml AS de_paylod_xml,
    FROM
    DE g, DM h, GM i, OP j
    WHERE
    h.dm_nbr = g.dm_nbr(+) and
    i.gm_nbr = h.gm_nbr(+) and
    j.op_nbr = i.op_nbr(+)
    +++++++++++++++++++++++++++++++++++++++++++++++++++++
    I am using above SQL select statement for fetching the XML records and this gives me all related xmls for each entity in a single record(OP, GM, DM. DE). Output of this SQL query is as below:
    Current O/P:
    <resultSet>
         <Record1>
              <OP_PAYLOD_XML1>
              <GM_PAYLOD_XML1>
              <DM_PAYLOD_XML1>
              <DE_PAYLOD_XML1>
         </Record1>
         <Record2>
              <OP_PAYLOD_XML2>
              <GM_PAYLOD_XML2>
              <DM_PAYLOD_XML2>
              <DE_PAYLOD_XML2>
         </Record2>
         <RecordN>
              <OP_PAYLOD_XMLN>
              <GM_PAYLOD_XMLN>
              <DM_PAYLOD_XMLN>
              <DE_PAYLOD_XMLN>
         </RecordN>
    </resultSet>
    Now i want to change my SQL query so that i get following output structure:
    <resultSet>
         <Record>
              <OP_PAYLOD_XML1>
              <GM_PAYLOD_XML1>
              <GM_PAYLOD_XML2> .......
              <GM_PAYLOD_XMLN>
              <DM_PAYLOD_XML1>
              <DM_PAYLOD_XML2> .......
              <DM_PAYLOD_XMLN>
              <DE_PAYLOD_XML1>
              <DE_PAYLOD_XML2> .......
              <DE_PAYLOD_XMLN>
         </Record>
         <Record>
              <OP_PAYLOD_XML2>
              <GM_PAYLOD_XML1'>
              <GM_PAYLOD_XML2'> .......
              <GM_PAYLOD_XMLN'>
              <DM_PAYLOD_XML1'>
              <DM_PAYLOD_XML2'> .......
              <DM_PAYLOD_XMLN'>
              <DE_PAYLOD_XML1'>
              <DE_PAYLOD_XML2'> .......
              <DE_PAYLOD_XMLN'>
         </Record>
    <resultSet>
    Appreciate your help in this regard!

    Hi,
    A few questions :
    How's your first query supposed to give you an XML output like you show ?
    Is there something you're not telling us?
    What's the content of, for example, <OP_PAYLOD_XML1> ?
    I don't think it's a good idea to embed the node level in the tag name, it would make much sense to expose that as an attribute.
    What's the db version BTW?

  • How to capture all the rows returned from a sql select query in CPO

    Hi,
      I am executing an sql select query which returns multiple rows. I need to capture the values of each row to specific variables. How do I proceed.
    Thanks,
    Swati

    The select activities  ("Select from Oracle," Select from SQL Server," etc.) against database already return tables.  Use one of the database adapters to do your select, and it will already be in a table form.  Just put your query in the select and identify the columns in your result table. The online help or the database adapter guides in the product documentation can help.

  • Reg: SQL select Query in BPEL process flow

    <p>
    Hi,
    I am suppose to execute a SQL select query (in BPEL Process flow) as mention below in JDeveloper using Database adapter.
    </p>
    <p>
    SELECT LENGTH, WIDTH, HEIGHT, WEIGHT,
    </p>
    <p>
    LENGTH*WIDTH* HEIGHT AS ITEM_CUBE
    </p>
    <p>
    FROM CUBE
    </p>
    <p>
    WHERE ITEM= &lt;xyz&gt;
    </p>
    <p>
    AND OBJECT= (SELECT CASE_NAME FROM CUBE_SUPPLIER WHERE ITEM=&lt;xyz&gt; AND SUPP_IND = &lsquo;Y')
    <strong>Now my question is:
    1.</strong> What does this "*" refer to in the query and how can I retrieve the value of LENGTH*WIDTH* HEIGHT from the query where LENGTH,WIDTH and HEIGHT are the individual field in the table.
    2.What does this " AS" refer to? If " ITEM_CUBE " is the alies for the table name "ITEM" to retrieve the value, then query shoud be evaluated as
    </p>
    <p>
    SELECT LENGTH, WIDTH, HEIGHT, WEIGHT,
    </p>
    <p>
    LENGTH*WIDTH* HEIGHT AS ITEM_CUBE
    </p>
    <p>
    FROM CUBE
    </p>
    <p>
    WHERE <strong>ITEM_CUBE.ITEM</strong>= &lt;xyz&gt;
    </p>
    <p>
    AND <strong>ITEM_CUBE.OBJECT</strong>= (SELECT CASE_NAME FROM CUBE_SUPPLIER WHERE ITEM=&lt;xyz&gt; AND SUPP_IND = &lsquo;Y')
    Is my assumption correct?
    Please suggest asap.
    Thanks...
    </p>
    <p>
    </p>

    Hi
    Thank for your reply!
    I have a nested select query which performs on two different table as shown below:
    <p>
    SELECT LENGTH, WIDTH, HEIGHT, WEIGHT,
    </p>
    <p>
    LENGTH*WIDTH* HEIGHT AS ITEM_CUBE
    </p>
    <p>
    FROM CUBE
    </p>
    <p>
    WHERE ITEM= &lt;abc&gt;
    </p>
    <p>
    AND OBJECT= (SELECT NAME FROM SUPPLIER WHERE ITEM=&lt;Item&gt; AND SUPP_IND = &lsquo;Y')
    I am using DB adapter of Oracle JDeveloper in BPEL process flow, where I can able to select only one master table in DB adapter say SUPPLIER and its attributes at a time.But as per my requirment I need to select both the table (CUBE and SUPPLIER) in a single adapter to execute my query.
    It can be achievable by using two DB adapter , One to execute the nested query and another to execute the main qyery considering value of nested query as a parameter.But I want to achieve it by using a single one.
    Am I correct with my concept?
    Please suggest how to get it ?
    </p>
    Edited by: user10259700 on Oct 23, 2008 12:17 AM

  • Parsing an OPEN SQL select statement

    Hi all,
      I want to parse an open SQL select statement to get the list of tables and the corresponding fields in the select statement.
      Is there some ABAP-internal syntax from the SAP Database Interface that does this? or is the only option to do this is to manually break the statement?
    Thanks.
    Girish

    Hi,
    I doubt if there is something like that available to use. It think you will have to write a parser for yourself.
    Regards

  • SQL SELECT statement Parent_child table and its related table..... HELP plz

    I have 2 tables
    Table Parent_child_table:
    ID | Parent_id | Name
    1 | NULL | Kitchen
    2 | 1 | Freezer
    3 | NULL | Garden
    4 | 3 | Grass
    Table Products:
    ID | parent_child_table_ID | Price | Comment
    1 | 2 | 111 | aaaa
    2 | 4 | 12 | vv
    I want to select Name from parent table where selected child ID are in PRODUCT table.....
    The result would like:
    |NAME|
    |Kitchen
    |Garden
    Can someone help with this SQL SELECT ?

    Raivis wrote:
    I have 2 tables
    Table Parent_child_table:
    ID | Parent_id | Name
    1 | NULL | Kitchen
    2 | 1 | Freezer
    3 | NULL | Garden
    4 | 3 | Grass
    Table Products:
    ID | parent_child_table_ID | Price | Comment
    1 | 2 | 111 | aaaa
    2 | 4 | 12 | vv
    I want to select Name from parent table where selected child ID are in PRODUCT table.....
    The result would like:
    |NAME|
    |Kitchen
    |Garden
    Can someone help with this SQL SELECT ?A guess
    select
       p.name
    from Parent_child_table p
    where p.parent_id is null
    and exists
    select
       null
    from Parent_child_table p1, products p2
    where p1.id = p2. parent_child_table_id
    and p1.parent_id = p.id
    )The reason it's a guess is because you've really done nothing to outline WHY you should get the results you say you would like. The more time you spend creating a clear question, the less time you'll have to spend weeding through useless answers.
    Cheers,

  • How to exit from SQL*Plus based on the return value of a SQL select stment?

    Hi
    I have a SQL script executed from SQL*Plus. I would like to know if SQL*Plus
    supports any kind of branching or exiting from script execution based on a
    returned value of a SQL select statement. I am on 9i.
    Regards,
    Tamas Szecsy

    in sqlplus, you have whenever
    ex:
    whenever sqlerror exit failure
    insert into ...
    -- if this fails, then you will be out
    insert into ...
    -- if this fails, then you will be out
    whenever sqlerror continue
    insert into ...
    -- if this fails, this continues
    insert into ...and you have PL/SQL
    declare x number;
    begin
    select count(*) into x from emp;
    if (x=14) then null; end if;
    end;
    /note that you can mix those in some case
    -- exit if there is no row in emp
    whenever sqlerror exit 1
    var dummy number
    exec select count(*) into :dummy from emp having count(*)!=0

  • Lookup by SQL select in ODS tables and source package

    Hi all
    I load FI data in ODS and need some extra info from older ODS records.
    In my Update rule for target InfoObject I created 2 SQL selects on Active Data and New data tables of ODS. Selects worked fine while testing them as separate program, but I got no data while data load.
    I guess, the data I need was in the same data package during data load. So I assume, besides Active/New data selects, I need to check data on SOURCE_PACKAGE. Is it possible on update rule level of InfoObject? Could you please, provide me some ABAP example?
    thanx in advance, points will be awarded.

    SELECT in field routine:
    ==========================================================
          DATA src_doc_no(10) TYPE c.
          DATA src_item_num(3) TYPE c.
          DATA src_year(5) TYPE c.
          DATA src_doc_typ(2) TYPE c.
      if ( COMM_STRUCTURE-AC_DOC_TYP = 'DD' or COMM_STRUCTURE-AC_DOC_TYP =
      'LD' ) and STRLEN( COMM_STRUCTURE-REF_KEY3 ) = 17.
         CONCATENATE COMM_STRUCTURE-REF_KEY3+0(4) '%' INTO src_year.
         src_item_num = COMM_STRUCTURE-REF_KEY3+15(3).
         src_doc_no = COMM_STRUCTURE-REF_KEY3+4(10).
    select from NEW data of ODS:
         SELECT AC_DOC_TYP into src_doc_typ
         FROM /BI0/AFIAR_O0340
         WHERE COMP_CODE = COMM_STRUCTURE-COMP_CODE
           AND DEBITOR = COMM_STRUCTURE-DEBITOR
           AND FISCVARNT = COMM_STRUCTURE-FISCVARNT
           AND AC_DOC_NO = src_doc_no
           AND ITEM_NUM = src_item_num
           AND FISCPER like src_year.
         endselect.
         if src_doc_typ = ''.
    select from ACTIVE data of ODS:
           SELECT AC_DOC_TYP into src_doc_typ
           FROM /BI0/AFIAR_O0300
           WHERE COMP_CODE = COMM_STRUCTURE-COMP_CODE
             AND DEBITOR = COMM_STRUCTURE-DEBITOR
             AND FISCVARNT = COMM_STRUCTURE-FISCVARNT
             AND AC_DOC_NO = src_doc_no
             AND ITEM_NUM = src_item_num
             AND FISCPER like src_year.
           endselect.
         endif.
         RESULT = src_doc_typ.
      endif.
    ============================================

  • Using column number inplace of column name in SQL Select statement

    Is there a way to run sql select statements with column numbers in
    place of column names?
    Current SQL
    select AddressId,Name,City from AddressIs this possible
    select 1,2,5 from AddressThanks in Advance

    user10962462 wrote:
    well, ok, it's not possible with SQL, but how about PL/SQL?As mentioned, using DBMS_SQL you can only really use positional notation... and you can also use those positions to get the other information such as what the column is called, what it's datatype is etc.
    CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2) IS
      v_v_val     VARCHAR2(4000);
      v_n_val     NUMBER;
      v_d_val     DATE;
      v_ret       NUMBER;
      c           NUMBER;
      d           NUMBER;
      col_cnt     INTEGER;
      f           BOOLEAN;
      rec_tab     DBMS_SQL.DESC_TAB;
      col_num     NUMBER;
      v_rowcount  NUMBER := 0;
    BEGIN
      -- create a cursor
      c := DBMS_SQL.OPEN_CURSOR;
      -- parse the SQL statement into the cursor
      DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
      -- execute the cursor
      d := DBMS_SQL.EXECUTE(c);
      -- Describe the columns returned by the SQL statement
      DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
      -- Bind local return variables to the various columns based on their types
      FOR j in 1..col_cnt
      LOOP
        CASE rec_tab(j).col_type
          WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); -- Varchar2
          WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);      -- Number
          WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);     -- Date
        ELSE
          DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);  -- Any other type return as varchar2
        END CASE;
      END LOOP;
      -- Display what columns are being returned...
      DBMS_OUTPUT.PUT_LINE('-- Columns --');
      FOR j in 1..col_cnt
      LOOP
        DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' - '||case rec_tab(j).col_type when 1 then 'VARCHAR2'
                                                                                  when 2 then 'NUMBER'
                                                                                  when 12 then 'DATE'
                                                         else 'Other' end);
      END LOOP;
      DBMS_OUTPUT.PUT_LINE('-------------');
      -- This part outputs the DATA
      LOOP
        -- Fetch a row of data through the cursor
        v_ret := DBMS_SQL.FETCH_ROWS(c);
        -- Exit when no more rows
        EXIT WHEN v_ret = 0;
        v_rowcount := v_rowcount + 1;
        DBMS_OUTPUT.PUT_LINE('Row: '||v_rowcount);
        DBMS_OUTPUT.PUT_LINE('--------------');
        -- Fetch the value of each column from the row
        FOR j in 1..col_cnt
        LOOP
          -- Fetch each column into the correct data type based on the description of the column
          CASE rec_tab(j).col_type
            WHEN 1  THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                         DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
            WHEN 2  THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                         DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_n_val);
            WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                         DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'));
          ELSE
            DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
            DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
          END CASE;
        END LOOP;
        DBMS_OUTPUT.PUT_LINE('--------------');
      END LOOP;
      -- Close the cursor now we have finished with it
      DBMS_SQL.CLOSE_CURSOR(c);
    END;
    SQL> exec run_query('select empno, ename, deptno, sal from emp where deptno = 10');
    -- Columns --
    EMPNO - NUMBER
    ENAME - VARCHAR2
    DEPTNO - NUMBER
    SAL - NUMBER
    Row: 1
    EMPNO : 7782
    ENAME : CLARK
    DEPTNO : 10
    SAL : 2450
    Row: 2
    EMPNO : 7839
    ENAME : KING
    DEPTNO : 10
    SAL : 5000
    Row: 3
    EMPNO : 7934
    ENAME : MILLER
    DEPTNO : 10
    SAL : 1300
    PL/SQL procedure successfully completed.
    SQL> exec run_query('select * from emp where deptno = 10');
    -- Columns --
    EMPNO - NUMBER
    ENAME - VARCHAR2
    JOB - VARCHAR2
    MGR - NUMBER
    HIREDATE - DATE
    SAL - NUMBER
    COMM - NUMBER
    DEPTNO - NUMBER
    Row: 1
    EMPNO : 7782
    ENAME : CLARK
    JOB : MANAGER
    MGR : 7839
    HIREDATE : 09/06/1981 00:00:00
    SAL : 2450
    COMM :
    DEPTNO : 10
    Row: 2
    EMPNO : 7839
    ENAME : KING
    JOB : PRESIDENT
    MGR :
    HIREDATE : 17/11/1981 00:00:00
    SAL : 5000
    COMM :
    DEPTNO : 10
    Row: 3
    EMPNO : 7934
    ENAME : MILLER
    JOB : CLERK
    MGR : 7782
    HIREDATE : 23/01/1982 00:00:00
    SAL : 1300
    COMM :
    DEPTNO : 10
    PL/SQL procedure successfully completed.
    SQL> exec run_query('select * from dept where deptno = 10');
    -- Columns --
    DEPTNO - NUMBER
    DNAME - VARCHAR2
    LOC - VARCHAR2
    Row: 1
    DEPTNO : 10
    DNAME : ACCOUNTING
    LOC : NEW YORK
    PL/SQL procedure successfully completed.
    SQL>

  • Save SQL select output as html page on another box.

    How can I save a simple sql select output on another server as a html page?

    Hi,
    You can use the Oracle product WebDB (Oracle Portal) to create reports in HTML over the DB (simplest way).
    Instead You can use SQL*Plus on the remote server (where You want to spool), enable the spool to file (using SPOOL) and create the select as
    SELECT 'html tags' &#0124; &#0124; field/s &#0124; &#0124; 'html tags'
    FROM your_table;Using this solution You have to manually "draw" the report.
    Hope this helps.
    Bye Max
    null

  • SQL select a concatination of entries from another table

    I am trying to select a few columns from one table and then add another column that is a concatination or names from another table that referances it as below. Is this possible to do in one select statement?
    table x1
    ID NAME
    1 Bob
    1 Tom
    2 Bill
    table x2
    ID NAMES
    1 Bob, Tom
    2 Bill
    3

    You mean string aggregation?
    If yes, then it is possible like this, if you are on 10g.
    SQL> create table x1 (id,name)
      2  as
      3  select 1, 'Bob' from dual union all
      4  select 1, 'Tom' from dual union all
      5  select 2, 'Bill' from dual
      6  /
    Tabel is aangemaakt.
    SQL> select id
      2       , rtrim(n,', ') names
      3    from ( select id
      4                , n
      5                , rn
      6             from x1
      7            model
      8                  partition by (id)
      9                  dimension by (row_number() over (partition by id order by null) rn)
    10                  measures (cast(name as varchar2(20)) n)
    11                  rules
    12                  ( n[any] order by rn desc = n[cv()] || ', ' || n[cv()+1]
    13                  )
    14         )
    15   where rn = 1
    16  /
            ID NAMES
             1 Bob, Tom
             2 Bill
    2 rijen zijn geselecteerd.There are several other (slower) techniques possible as well. You can find them by using the search function on this forum.
    Regards,
    Rob.

Maybe you are looking for

  • Payroll Problem

    For an employee, leaving action been processed in June month, however, his details are coming in July payroll without any value What could be the reason?

  • There should be a way to easly switch between wifi and cellular data

    I think apple should put wifi icon and cellular data icon on the notification bar so we can change between them easily or even closing them both. So other smart phone like Samsung did it from a long time and its really easier way so Apple as the grea

  • Disk Utility backup not working under Cmd R mode

    I upgraded my OS to 10.8.2. After doing so, when I do my normal system backup with Disk Utility, the system goes into sleep mode and the backup stops. I've done this many times in the past so I am not new to this.  I've read a few articles/posts with

  • How do I add an add on not listed using 3.6 version

    I must use version 3.6 for my job and I must add an application that I have downloaded, however, i see nowhere I can add the the file as an add on. I accidentally downloaded 5.0 version and had the option but don't see the option in ver 3.6

  • In design CS2 has it been dumped completely by this awful company

    My problem is that Indesign CS2 wont open any longer. I bought it as a bundle and paid a huge sum for the full Creative suite. I was told at the time that I could run a separate copy on my laptop at the time. Later when I tried to do that I found tha