Need help in framing an SQL query

Hi ,
Requirement is that
Let’s say I have a table say X
I am passing two input params from UI and in DAO i am querying these input prams against the table X(has c1,c2 as columns ) (as it has two columns mapping the input params A,B from UI).
if either one or Both of the input params matches ,only then i should fetch the records accordingly. It's understood that there won't be a scenario that both input params are null from UI.
I have three conditions here,
1.     A match against X, B doesnt Match
2.     B match against X, A doesnt Match
3.     Both A & B match against X
if i use let's say,
SELECT *FROM X WHERE (c1= A OR c2= B) .
•     if A match against X B doesnt Match It is fetching all the records matching A - requirement fullfilled
•     B match against X A doesnt Match It is fetching all the records matching B- requirement fullfilled.
•     Both A & B match against X It is fetching all the records from the table matching the first condition (which here is A) . requirement not fullfilled.
I am thinking of using the following query but I need to frame it in a way that based on ACHK & BCHK we need to add the conditions.
SELECT CASE WHEN C1 = A THEN 0 ELSE 9 END AS ACHK, CASE WHEN C2 = B THEN 0 ELSE 9 END AS BCHK FROM X
Based on ACHK & BCHK append the conditions. i.e.
IF ACHK = 0 AND BCHK = 0 THEN
AND C1 = A AND C2 = B
ELSE
AND (C1 = A OR C2 = B)
Please help.

Hi,
963022 wrote:
Would be glad if you can shed some light on role of DENSE_RANK here (ofcourse i did read the forums but i am confused on what basis a row is ranked).Complicated queries and expressions are usually built of smaller, simpler parts. To understand how the big, complicated thing works, look first at the smaller, simpler components of it, and make sure you understand how they work.
In this case, the query is composed of a sub-query and a main query. Start by looking at the sub-query only. Display all rows and all columns of the sub-query.
Break apart the complicated components of that sub-query. Rnk depends on an ORDER BY clause, but the expression used in that ORDER BY clause isn't displayed anywhere. Copy and display just that expression. (I called this case_1_2 in the query below.) Even that may be too complicated to understand, so break it apart. Case_1_2 is formed by adding 2 smaller CASE expressions; in the query below, I displayed each of the in separate columns (case_1 and case_2).
So here's a query you might use to understand and debug the query I posted:
WITH     targets          AS
     SELECT     'ABC' AS c1, 10 AS c2  FROM dual     UNION ALL
     SELECT     'ABC',          20            FROM dual     UNION ALL
     SELECT     'FOO',          10            FROM dual     UNION ALL
     SELECT     'FOO',          20            FROM dual     UNION ALL
     SELECT     'FOO',          99            FROM dual
,     got_rnk          AS
     SELECT     x.c1, x.c2
     ,     t.c1          AS target_c1
     ,     t.c2          AS target_c2
     ,     DENSE_RANK () OVER ( PARTITION BY  t.c1, t.c2
                               ORDER BY          CASE
                                             WHEN  x.c1  = t.c1
                                     THEN  1
                                     ELSE  0
                                         END
                               + CASE
                                             WHEN  x.c2  = t.c2
                                     THEN  2
                                     ELSE  0
                                         END
                         DESC
                       )          AS rnk
--     *****  DEBUGGING SECTION  *****     The following columns are included only
--                                       to see how the function above works.
     ,                               CASE
                                             WHEN  x.c1  = t.c1
                                     THEN  1
                                     ELSE  0
                                         END
                               + CASE
                                             WHEN  x.c2  = t.c2
                                     THEN  2
                                     ELSE  0
                                         END           AS case_1_2
     ,                               CASE
                                             WHEN  x.c1  = t.c1
                                     THEN  1
                                     ELSE  0
                                         END           AS case_1
     ,                            CASE
                                             WHEN  x.c2  = t.c2
                                     THEN  2
                                     ELSE  0
                                         END           AS case_2
--     *****  END OF DEBUGGING SECTION  *****
     FROM     targets  t
     JOIN           x  ON   x.c1     = t.c1
                   OR   x.c2     = t.c2
--     The following main query is only for debugging
SELECT       *
FROM       got_rnk
ORDER BY  target_c1, target_c2
,            rnk
;Output:
              TARGET TARGET          CASE
C1         C2 _C1       _C2    RNK   _1_2 CASE_1 CASE_2
ABC        10 ABC        10      1      3      1      2
ZZZ        10 ABC        10      2      2      0      2
ABC         5 ABC        10      3      1      1      0
ABC         6 ABC        10      3      1      1      0
ABC         7 ABC        10      3      1      1      0
ABC         1 ABC        10      3      1      1      0
ABC         3 ABC        10      3      1      1      0
ABC         2 ABC        10      3      1      1      0
ABC         8 ABC        10      3      1      1      0
ABC         9 ABC        10      3      1      1      0
ABC         4 ABC        10      3      1      1      0
ZZZ        20 ABC        20      1      2      0      2
ABC        10 ABC        20      2      1      1      0
ABC         2 ABC        20      2      1      1      0
ABC         1 ABC        20      2      1      1      0
ABC         9 ABC        20      2      1      1      0
ABC         8 ABC        20      2      1      1      0
ABC         7 ABC        20      2      1      1      0
ABC         6 ABC        20      2      1      1      0
ABC         5 ABC        20      2      1      1      0
ABC         4 ABC        20      2      1      1      0
ABC         3 ABC        20      2      1      1      0
ABC        10 FOO        10      1      2      0      2
ZZZ        10 FOO        10      1      2      0      2
ZZZ        20 FOO        20      1      2      0      2Study this output to see how the different components work.
For example, the first 12 rows of output show what we found when we were looking for ('ABC', 10). There were 12 rows in table x that had either ca='ABC' or c2=10 (or both). We used the rnk column to find the best match: lower numbers mean better matches. How did we do that? By using the DENSE_RANK function with a DESCending order by clause, that is, we used <tt> DENSE_RANK () OVER (... ORDER BY exp DESC) </tt>, which means that higher values of exp produce lower values from DENSE_RANK. What is exp? It's the column I called case_1_2. As you can see, when there was a perfect match ('ABC', 10), then case_1_2 had the value 3. Less perfect matches got lower values of case_1_2; for example ('ZZZ', 10) only had 2 in the case_1_2 column, and ('ABC', 5) only had 1. Why did case_1_2 have values of 3, 2 or 1 on those rows? Well, it's the sum of case_1 and case_2, so look at those individual columns, and see how they are computed.

Similar Messages

  • Need help in framing an SQL query - Sample data and output required is mentioned.

    Sample data :
    ID Region State
    1 a A1
    2 b A1
    3 c B1
    4 d B1
    Result should be :
    State Region1 Region2
    A1 a b
    B1 c d

    create table #t (id int, region char(1),state char(2))
    insert into #t values (1,'a','a1'),(2,'b','a1'),(3,'c','b1'),(4,'d','b1')
    select state,
     max(case when region in ('a','c') then region end) region1,
      max(case when region in ('b','d') then region end) region2
     from #t
     group by state
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Need help in rewriting a sql query

    Can any one please tell me if there is any utility that can help me correcting the sql I have I need to tune the query as its taking lot of time. I want to use some tool that will help me re-formating the query.
    Any help in this regard will be highly appreciated.

    If you think that Oracle SQL Tuning Tools like SQL Tuning Advisor and SQL Access Advisor are not helping.
    You might look into thrid party tools like Quest- SQL Navigator and TOAD.
    But I don't advise this based on the following:
    Re: Oracle Third Party Tools and Oracle Database
    Oracle have enough tools of its own to satisfy the various needs.
    Adith

  • Need help in Report From SQL Query

    Hi All,
    I am facing a problem with a report. I need your help.
    I am creating a Report From SQL Query (Portal) with some arguments passed at runtime. I am able to view the output, if the query returns few rows ( arount 1000 rows). But for some inputs it needs to generate >15000 records, at this point the page is getting time out (i think!) and showing error page. I am able to execute query from the SQL Plus console ot using TOAD editor. Here the query is not taking more that 2 mins time to show the result.
    If i am executing from Portal i observed that, once i give the appropriate input and hit submit button a new oracle process is getting created for the query on UNIX (I am usign "TOP" command to check processes). The browser page will be shown error page after 5 minutes (i am assuming session time out!) , but on the backend the process will be executed for more than 30 mins.
    I tried also increase the page time out in httpd.conf, but no use.
    The data returned as a result of the query is sized more than 10 MB. Is caching this much data is possible by the browser page? is the returned data is creating any problem here.
    Please help me to find appropriate reasone for the failure?

    user602513 wrote:
    Hi All,
    I am facing a problem with a report. I need your help.
    I am creating a Report From SQL Query (Portal) with some arguments passed at runtime. I am able to view the output, if the query returns few rows ( arount 1000 rows). But for some inputs it needs to generate >15000 records, at this point the page is getting time out (i think!) and showing error page. I am able to execute query from the SQL Plus console ot using TOAD editor. Here the query is not taking more that 2 mins time to show the result.
    If i am executing from Portal i observed that, once i give the appropriate input and hit submit button a new oracle process is getting created for the query on UNIX (I am usign "TOP" command to check processes). The browser page will be shown error page after 5 minutes (i am assuming session time out!) , but on the backend the process will be executed for more than 30 mins.
    I tried also increase the page time out in httpd.conf, but no use.
    The data returned as a result of the query is sized more than 10 MB. Is caching this much data is possible by the browser page? is the returned data is creating any problem here.
    Please help me to find appropriate reasone for the failure?Do you get any errors or warnings or it is just the slow speed which is the issue?
    There could be a variety of reasons for the delayed processing of this report. That includes parameter settings for that page, cache settings, network configurations, etc.
    - explore best optimization for your query;
    - evaluate portal for best performance configuration; you may follow this note (Doc ID: *438794.1* ) for ideas;
    - third: for that particular page carrying that report, you can use caching wisely. browser cache is neither decent for large files, nor practical. instead, explore the page cache settings that portal provides.
    - also look for various log files (application.log and apache logs) if you are getting any warnings reflecting on some kind of processing halt.
    - and last but not the least: if you happen to bring up a portal report with more than 10000 rows for display then think about the usage of the report. Evaluate whether that report is good/useful for anything?
    HTH
    AMN

  • Need Help with Creating the SQl query

    Hi,
    SQL query gurus...
    INFORMATION:
    I have two table, CURRENT and PREVIOUS.(Table Defs below).
    CURRENT:
    Column1 - CURR_PARENT
    Column2 - CURR_CHILD
    Column3 - CURR_CHILD_ATTRIBUTE 1
    Column4 - CURR_CHILD_ATTRIBUTE 2
    Column5 - CURR_CHILD_ATTRIBUTE 3
    PREVIOUS:
    Column1 - PREV_PARENT
    Column2 - PREV_CHILD
    Column3 - PREV_CHILD_ATTRIBUTE 1
    Column4 - PREV_CHILD_ATTRIBUTE 2
    Column5 - PREV_CHILD_ATTRIBUTE 3
    PROBLEM STATEMENT
    Here the columns 3 to 5 are the attributes of the Child. Lets assume that I have two loads, One Today which goes to the CURRENT table and one yesterday which goes to the PREVIOUS table. Between these two loads there is a CHANGE in the value for Columns either 3/4/5 or all of them(doesnt matter if one or all).
    I want to determine what properties for the child have changed with the help of a MOST efficient SQL query.(PARENT+CHILD is unique key). The Database is ofcourse ORACLE.
    Please help.
    Regards,
    Parag

    Hi,
    The last message was not posted by the same user_name that started the thread.
    Please don't do that: it's confusing.
    Earlier replies give you the information you want, with one row of output (maximum) per row in current_tbl. There may be 1, 2 or 3 changes on a row.
    You just have to unpivot that data to get one row for every change, like this:
    WITH     single_row  AS
         SELECT     c.curr_parent
         ,     c.curr_child
         ,     c.curr_child_attribute1
         ,     c.curr_child_attribute2
         ,     c.curr_child_attribute3
         ,     DECODE (c.curr_child_attribute1, p.prev_child_attribute1, 0, 1) AS diff1
         ,     DECODE (c.curr_child_attribute2, p.prev_child_attribute2, 0, 2) AS diff2
         ,     DECODE (c.curr_child_attribute3, p.prev_child_attribute3, 0, 3) AS diff3
         FROM     current_tbl    c
         JOIN     previous_tbl   p     ON  c.curr_parent     = p.prev_parent
                                AND c.curr_child     = p.prev_child
         WHERE     c.curr_child_attribute1     != p.prev_child_attribute1
         OR     c.curr_child_attribute2     != p.prev_child_attribute2
         OR     c.curr_child_attribute3     != p.prev_child_attribute3
    ,     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL <= 3
    SELECT     s.curr_parent     AS parent
    ,     s.curr_child     AS child
    ,     CASE     c.n
              WHEN  1  THEN  s.curr_child_attribute1
              WHEN  2  THEN  s.curr_child_attribute2
              WHEN  3  THEN  s.curr_child_attribute3
         END          AS attribute
    ,     c.n          AS attribute_value
    FROM     single_row     s
    JOIN     cntr          c     ON     c.n IN ( s.diff1
                                    , s.diff2
                                    , s.diff3
    ORDER BY  attribute_value
    ,            parent
    ,            child
    ;

  • Need help to where small sql query

    { names           numbers                         types
    id | name | | id | phone | who | type | | id | type |
    | 1 | jenny | | 1 | 867-5309 | 1 | 3 | | 1 | home |
    | 2 | tom | | 2 | 555-1212 | 3 | 1 | | 2 | cell |
    | 3 | smith | | 3 | 364-4311 | 3 | 2 | | 3 | work |
    | 4 | amy | | 4 | 936-2828 | 4 | 3 | | 4 | fax |
    | 5 | 525-8722 | 3 | NULL | -----------
    i am trying to get out put like this ,:
    name type phone
    | smith | home | 555-1212 |
    | smith | cell | 364-4311 |
    | smith | NULL | 525-8722 |
    is it posiible to get tree time "smith " in the name column ,that is confusing me a lot
    please can any one give idea how to solve this }
    Edited by: user4463478 on May 20, 2009 5:38 PM
    Edited by: user4463478 on May 21, 2009 11:51 AM
    Edited by: user4463478 on May 21, 2009 11:52 AM

    What is your table structure? It is confusing. Post your sample input, output, table strucutre etc between {noformat}{noformat} and {noformat}{noformat}
    And it looks like this.
    and Cheers
    Sarma.

  • Help me write a SQL query; urgent

    Hi, can somebody please help me write a SQL query.
    I have 3 tables each with the same column names (Col1, Col2, Col3). Col1 is PK with Unique Constraint.
    I wanted to add values of Col2 and Col3 (from all 3 tables) and put it in a separate table (i.e aggregated) of all values found in Col1.
    Does anybody help me please ?
    thanks alot.

    Please don't mark your question as urgent. You've been around here long enough that you should know that it will not get your question anwered any faster, and may just irritate people into not answering at all.
    I'm not sure exactly what you want.
    Are you saying you want t1.c2 + t1.c3 + t2.c2 + t2.c3+ t3.c2 + t3.c3 for the rows that have the same c1 in all three tables?
    If so, it would be like this, I think: insert into t4
    select t1.c1
    , t1.c2 + t1.c3 + t2.c2 + t2.c3+ t3.c2 + t3.c3
    from t1, t2, t3
    where t2.c1 = t1.c1
    and t3.c1 = t1.c1If that's not what you want, please clarify.
    And next time maybe you should post your SQL question in a SQL forum.

  • Need help to write an interesting query

    I need some help in framing the query for the following scenario.
    I have three tables (in general)
    Departments
    DNO (PK)
    DNAME
    Employees
    DNO (FK to DNO in Departments)
    ENO (PK)
    CODE
    History
    seqid (PK)
    ENO (FK to ENO in Employees)
    The summary of the data in Employees table looks like below:
    DNo           No of employees
    10              10
    20               5
    30               8so there will be total of 23 records in employees table. I want to check if all the 10 employees from dept 10 are existing in history table and if exists I want to display the dno and dname from the employees and departments tables respectively. Even if the history table has 9 employees out of 10 from employees table I don't want the query to retrieve that dept details.
    Can any one help me with this?
    Meanwhile I will also try my level best and let you people know if I come up with anything.
    Thanks for your time

    Here the example that will help you.
    emp_test is the history table for you. You can change ct>9SQL> SELECT * FROM
      2  ( SELECT empno ,
      3          ename ,
      4       e.deptno,dname,
      5       COUNT(*) OVER(PARTITION BY e.deptno ORDER BY e.deptno) ct
      6     FROM EMP e ,DEPT d
      7     WHERE e.deptno=d.deptno
      8     AND EXISTS (SELECT 'x' FROM EMP_TEST T
      9                 WHERE T.empno=e.empno))
    10  WHERE ct>3;
         EMPNO ENAME          DEPTNO DNAME                  CT
          7499 ALLEN              30 SALES                   4
          7698 BLAKE              30 SALES                   4
          7654 MARTIN             30 SALES                   4
          7521 WARD               30 SALES                   4
    SQL> set linesize 300
    SQL> select * from emp_test;
         EMPNO ENAME                JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 SMITH                CLERK           7902 17-DEC-80      800.2                    20
          7499 ALLEN                SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD                 SALESMAN        7698 22-FEB-81       1250        500         30
          7566 JONES                MANAGER         7839 02-APR-81       2975                    20
          7654 MARTIN               SALESMAN        7698 28-SEP-81       1250       1400         30
          7698 BLAKE                MANAGER         7839 01-MAY-81       2850                    30
          7782 CLARK                MANAGER         7839 09-JUN-81       2450                    10
    7 rows selected.
    SQL> select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-80      800.2                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
          7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
          7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
          7839 KING       PRESIDENT            17-NOV-81       5000                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
          7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
          7900 JAMES      CLERK           7698 03-DEC-81        950                    30
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    10formatted
    Message was edited by:
    devmiral

  • Please help me with this SQL query

    I am practicing SQL queries and have come across one involving fetching data from 3 different tables.
    The three tables are as below
    <pre>
    Country
    location_id          country
    loc1          Spain
    loc2          England
    loc3          Spain
    loc4          USA
    loc5          Italy
    loc6          USA
    loc7          USA
    </pre>
    <pre>
    User
    user_id location_id
    u1 loc1
    u2 loc1
    u3 loc2
    u4 loc2
    u5 loc1
    u6 loc3
    </pre>
    <pre>
    Post
    post_id user_id
    p1 u1
    p2 u1
    p3 u2
    p4 u3
    p5 u1
    p6 u2
    </pre>
    I am trying to write an SQL query - for each country of users, display the average number of posts
    I understand the logic behind this that we first need to group together all the locations and then the users belonging to one country and then find the average of their posts.
    But, i'm having a difficulty in putting this in SQL form. Could someone please help me with this query.
    Thanks.

    select
    country.country,
    count(*) Totalpostspercountry,
    count(distinct post.user_id) Totaldistincuserspercountry,
    count(*)/count(distinct post.user_id) Avgpostsperuserbycountry
    from
    country, muser, post
    where country.location_id = muser.location_id
    and muser.user_id = post.user_id
    group by country.country
    The output is like this for your sample data - hope this is what you were looking for :)
    COUNTRY,TOTALPOSTSPERCOUNTRY,TOTALDISTINCUSERSPERCOUNTRY,AVGPOSTSPERUSERBYCOUNTRY
    England,1,1,1,
    Spain,5,2,2.5,

  • Continuation-Please help with a complex sql query

    Hi all,
    Thanks a lot for your suggestions and inputs in the last thread of this post.
    With the help of your suggested approach,i went ahead and was able to get some more data in the format as needed..I worked on gradually adding one table after another exactly as the data is required stepwise.But,still I am facing issues with displaying them.
    there are many issues I am not able to do and would appreciate if you please have a look at my latest modified SELECT given below and help me writing it to get the display as needed.
    Below,is the attempted query i tried out using your inputs.But,am stuck and need your help in writing it.
    **Here,there is 1 ->MANY lines for the t_objective_id--->This has many learning_record_ids which i want to group by the unique objective_id.
    Also,prior to that,there is a tplan_id---->which has MANY t_objective_id's
    SELECT DECODE (LAG (firstname, 1, 0) OVER (ORDER BY firstname),
                   firstname, ' ',
                   firstname
                  ) firstname,
           DECODE (LAG (emplid, 1, 0) OVER (ORDER BY emplid),
                   emplid, ' ',
                   emplid
                  ) emplid,
           DECODE (LAG (tplan_name, 1, 0) OVER (ORDER BY tplan_name),
                   tplan_name, ' ',
                   tplan_name
                  ) tplan_name,
                  tplan_id,
                  DECODE (LAG (activities, 1, 0) OVER (ORDER BY activities),
                   activities, ' ',
                   activities
                  ) activities,
                  activities,
                  --activities,
           DECODE (LAG (t_objective_id, 1, 0) OVER (ORDER BY t_objective_id),
                   t_objective_id, ' ',
                   t_objective_id
                  ) t_objective_id,           
                   completed_activities,required_credits,
          DECODE (LAG (learning_record_id, 1, 0) OVER (ORDER BY learning_record_id),
                   learning_record_id, ' ',
                   learning_record_id
                  ) learning_record_id,           
                   catalog_item_name,catalog_item_type           
      FROM (SELECT test_cp.firstname, test_op.emplid, tp.tplan_name,tp.tplan_id,FN_TP_GET_CMPLTD_ACT_CNT(tp.tplan_id,test_lp.lp_person_id,'1862') activities,
                   test_tpo.t_objective_id,
                   (  fn_tp_obj_comp_req_act_cdt (test_lp.lp_person_id,
                                                  tp.tplan_id,
                                                  test_tpo.t_objective_id,
                                                  tp.is_credit_based
                    + fn_tp_obj_comp_opt_act_cdt (test_lp.lp_person_id,
                                                  tp.tplan_id,
                                                  test_tpo.t_objective_id,
                                                  tp.is_credit_based
                   ) completed_activities,test_tpo.required_credits,lr.learning_record_id,lr.catalog_item_name,lr.catalog_item_type
              FROM test_learning_plan test_lp,
                   test_training_plan tp,
                   test_person test_cp,
                   test_org_person test_op,test_tp_learning_activity test_tplplr,
                   test_tp_objective test_tpo,test_learning_record lr,test_train_obj_activity tpobjact
             WHERE test_lp.lp_person_id = '1862188559'
               AND test_cp.person_id = test_lp.lp_person_id
               AND tp.tplan_id = 'tplan200811200632352287621599'
               AND test_tpo.t_objective_id = tpobjact.t_objective_id
               AND test_lp.LP_CATALOG_HIST_ID = tp.tplan_id
               AND test_tplplr.tp_lp_lr_id =test_lp.learning_plan_id
               AND test_tplplr.activity_lp_lr_id = lr.learning_record_id
               AND lr.LR_CATALOG_HISTORY_ID = tpobjact.activity_id
               AND test_op.o_person_id = test_cp.person_id
               AND test_tpo.tplan_id = tp.tplan_id)
    If we see the outer SELECT ---then one of the main issues is for EACH t_objective_id----->There are n learning_record_ids.
    But,this select only shows 1 learning_record_id for each objective_id which is wrong.
    Similarly,the data displayed isnot proper.
    Below is the way I am getting the data now from the above SELECT.
    Note:- FIRSTNAME is not correctly displayed.
    FIRSTNAME     EMPLID     TPLAN_NAME     TPLAN_ID     ACTIVITIES     ACTIVITIES_1  
                      001                TP1          tplan1          5          5
    TESTNAME                                              tplan1           5          
    Continuation of the other columns of the same rows--**couldnt paste it properly so.
    T_OBJECTIVE_ID     COMPLETED_ACTIVITIES     REQUIRED_CREDITS     LEARNING_RECORD_ID        CATALOG_ITEM_NAME     CATALOG_ITEM_TYPE
              obj1               1                         5                         lr1                            C1                          Course
                    obj2               4                        4          

    Something like this might solve your problem ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>
    satyaki>select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7521 WARD       SALESMAN        7698 22-FEB-81     226.88        500         30
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1815       1400         30
          7788 SCOTT      ANALYST         7566 19-APR-87     598.95                    20
          7839 KING       PRESIDENT            17-NOV-81       7260                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81       2178          0         30
          7876 ADAMS      CLERK           7788 23-MAY-87     159.72                    20
          7900 JAMES      CLERK           7698 03-DEC-81     1379.4                    30
          7902 FORD       ANALYST         7566 03-DEC-81    5270.76                    20
          7934 MILLER     CLERK           7782 23-JAN-82     1887.6                    10
          7566 Smith      Manager         7839 23-JAN-82       1848          0         10
          7698 Glen       Manager         7839 23-JAN-82       1848          0         10
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7599 BILLY      ANALYST         7566 10-JUN-09       4500                    30
    12 rows selected.
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>
    satyaki>
    satyaki>
    satyaki>select decode(lag(job,1,null) over(order by job),'CLERK','CK',
      2                                                   'SALESMAN', 'SM',
      3                                                   'ANALYST','AL',
      4                                                   'BO') res
      5  from emp;
    RE
    BO
    AL
    AL
    AL
    CK
    CK
    CK
    BO
    BO
    BO
    SM
    RE
    SM
    12 rows selected.
    Elapsed: 00:00:00.01
    satyaki>
    satyaki>
    satyaki>select MAX(decode(lag(job,1,null) over(order by job),'CLERK','CK',
      2                                                   'SALESMAN', 'SM',
      3                                                   'ANALYST','AL',
      4                                                   'BO')) res
      5  from emp;
    select MAX(decode(lag(job,1,null) over(order by job),'CLERK','CK',
    ERROR at line 1:
    ORA-30483: window  functions are not allowed here
    Elapsed: 00:00:00.01
    satyaki>
    satyaki>select MAX(res)
      2  from (
      3          select decode(lag(job,1,null) over(order by job),'CLERK','CK',
      4                                                           'SALESMAN', 'SM',
      5                                                           'ANALYST','AL',
      6                                                           'BO') res
      7          from emp
      8     );
    MA
    SM
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>Regards.
    Satyaki De.

  • Need Help with Formula using SQL maybe

    I need help!  I work with Crystal reports XI and usually manage just fine with the Formula editor but his one I think will require some SQL and I am not good at that.
    We are running SQL 2000 I think (Enterprise Manager 8.0)  Our sales people schedule activities and enter notes for customer accounts.  Each is stored in a separate table.  I need to find activities that are scheduled 240 days into the future and show the most recent note that goes with the account for which that activity is scheduled.
    The two tables, Activities and History, share the an accountID field in common that links them to the correct customer account.   I want to look at dates in the Startdate.Activities field more than 240 days in the future and show the most recent note from the History table where the accountid's match. I figure my query will contain a join on AccountID.Activities and AccountID.History used with Max(completedate.History) but I do not understand how to word it.
    I would like to perform all this in crystal if possible.  I humbly request your help.
    Membery

    You SQL would look something like this...
    SELECT
    a.AccountID,
    a.BlahBlahBlah, -- Any other fields you want from the Activities table
    h.LastComment
    FROM Activities AS a
    LEFT OUTER JOIN History AS h ON a.AccountID = h.AccountID
    WHERE (a.ActivityDate BETWEEN GetDate() AND DateAdd(dd, 240, GetDate()))
    AND h.HistoryID IN (
         SELECT MAX(HistoryID)
         FROM History
         GROUP BY AccountID)
    This method assumes that the History table has a HistoryID that increments up automatically each time a new comment is added... So a comment made today would always have a higher HistoryID that one made yesterday.
    If I'm wrong and there is no HistoryID or the HistoryID doesn't increment in a chronological fashion, it can still be done but the code is a bit more complex.
    HTH,
    Jason

  • Need help to change BO generated query at universe leavel

    Hi
    Is there any possiblity to change sql at universe leavel.Kindly help me i am new to designer.
    The below is the BO generated query.
    SELECT specObjID 
    FROM SpecObj 
    WHERE SpecClass = dbo.fSpecClass('UNKNOWN') 
    Users are not intrested to go for coustomised sql in report leavel.
    I need to change the above sql accordingly due to some performance issues.
    The feilds that specify in the where clause SpecClass = dbo.fSpecClass('UNKNOWN')  move to from clause.
    Like below
    SELECT specObjID 
    FROM SpecObj ,SpecClass = dbo.fSpecClass('UNKNOWN') 
    WHERE 
    Kindly suggest me greatly appriciated.
    Thanks.
    Raj

    HI,
    As per your expectation query like below is not possible to give condition in from clause as per my understand,
    SELECT specObjID
    FROM SpecObj ,SpecClass = dbo.fSpecClass('UNKNOWN')
    WHERE
    I think your expected result can be achieved by giving condition while creating the object SpecObj.
    Steps:
    Go to universe, then edit the object SpecObj there you can give the where clause condition
    WHERE SpecClass = dbo.fSpecClass('UNKNOWN')
    This will increase your performance.
    Regrds,
    Ragoth.C

  • Need help with min max sql

    hi all, forgot i had a user name and password and haven't needed help for quite a bit since i didn't do sql for a while but now i'm back at reporting again...
    Here is a sample table as i remember it:
    Item     Date     Time     Time Frame     Duration     Duration Frame
    A     20100926     0     5     500     10
    A     20100926     600     10     500     30
    A     20100926     1500     12     100     30
    B     20100926     1800     28     200     40
    B     20100926     2200     6     150     70
    B     20100926     2600     15     600     60
    B     20100926     3600     30     200     70
    Results Set (expected):                         
    Item     Date     Time     Total Duration          
    A     20100926     0     1600:20     --basically max (time+duration) - min(time+duration)     
    B     20100926     1800     2000:00
    Sorry, but. I didnt put my sql statement as I wasn't planning on posting and left it at work, but, i've been looking on internet and people say to use min/max function and i've attenpted it with it works with just this table (without grouping). But as soon as i group it the values seem to mess up.
    Last i remembered it gave me:
    Item     Date     Time     Total Duration          
    A     20100926     0     1600:30     --basically max(time+duration) - min(time+duration)     
    B     20100926     1800     2000:70
    I think it's looking at max duration which is 30&70 and hence it retrurns those values in the result set. Is it because of the max function hence it's returning this value? any help is appreciated. thanks
    Edited by: stanleyho on Sep 30, 2010 4:44 PM

    Okay, here we go again, repost, hopefully okay this time:
    Hi Madhu, okay, just got to work: I am using TOAD and working in Oracle 10g. Here is my table structure and the query i use to try and get what I am looking for:
    There is one extra table but that is only used to link these two tables listed below so i didn't bother posting it.
    TABLE: TX_RECON_INSTANCE_VIEW
    ColumnName ColID DataType Null
    CHANNEL_CODE 3 VARCHAR2 (4 Char) N
    DURATION 8 NUMBER (10) N
    DURATION_FRAME 9 NUMBER (2) N
    REAL_TIME 6 NUMBER (10) N
    REAL_TIME_FRAME 7 NUMBER (2) N
    ITEM_ID 4 NUMBER Y
    TX_DATE 2 CHAR (8 Byte) N
    TX_ID 1 NUMBER (9) N
    TX_TYPE 13 VARCHAR2 (4 Char) N
    TABLE: TX_SCHEDULE
    ColumnName ColID PK Null DataType
    TX_TYPE 22 N VARCHAR2 (4 Char)
    TX_ID 1 1 N NUMBER (9)
    TX_DATE 2 N CHAR (8 Byte)
    SCHEDULE_TIME_FRAME 9 N NUMBER (2)
    SCHEDULE_TIME 8 N NUMBER (10)
    REAL_TIME 10 N NUMBER (10)
    DURATION_FRAME 13 N NUMBER (2)
    DURATION 12 N NUMBER (10)________________________________________
    And the data and results:
    TX_ID TX_DATE REAL_TIME REAL_TIME_FRAME DURATION DURATION_FRAME ITEM_ID AS RUN TIME AS RUN DURATION SCHEDULED TIME SCHEDULED DURATION SCHEDULE_TIME SCHEDULE_TIME_FRAME DURATION_1 DURATION_FRAME_1
    1651000 20100710 0 0 545 20 1234 00:00:00:00 00:09:05:20 00:00:00:00 00:09:05:20 0 0 545 20
    1752223 20100710 667 12 281 7 1234 00:11:07:12 00:04:41:07 00:11:07:10 00:04:41:07 667 10 281 7
    1846501 20100710 1071 13 335 9 1234 00:17:51:13 00:05:35:09 00:17:50:09 00:05:35:09 1070 9 335 9
    2001102 20100710 1525 6 249 14 1234 00:25:25:06 00:04:09:14 00:25:22:08 00:04:09:14 1522 8 249 14
    3246669 20100710 1800 0 586 2 1235 00:30:00:00 00:09:46:02 00:30:00:00 00:09:46:02 1800 0 586 2
    4456822 20100710 2492 16 276 5 1235 00:41:32:16 00:04:36:05 00:41:32:16 00:04:36:05 2492 16 276 5
    1253168 20100710 2890 15 222 17 1235 00:48:10:15 00:03:42:17 00:48:10:15 00:03:42:17 2890 15 222 17
    1112456 20100710 3277 18 297 0 1235 00:54:37:18 00:04:57:00 00:54:35:10 00:04:57:00 3275 10 297 0
    Grouped results set:
    TX_DATE ITEM_ID AS RUN TIME AS RUN DURATION SCHEDULED TIME SCHEDULED DURATION
    20100710 1234 00:00:00:00 00:29:34:20 00:00:00:00 00:29:31:20
    20100710 1235 00:30:00:00 00:29:34:17 00:30:00:00 00:29:32:17
    --> SCHEDULED DURATION "00:29:31:20" is not correct as it should be (00:25:22:08+00:04:09:14)-(00:00:00:00)=00:29:31:22
    --> see expected results below
    Expected results:
    TX_DATE ITEM_ID AS RUN TIME AS RUN DURATION SCHEDULED TIME SCHEDULED DURATION
    20100710 1234 00:00:00:00 00:29:34:20 00:00:00:00 00:29:31:22
    20100710 1235 00:30:00:00 00:29:34:18 00:30:00:00 00:29:34:10________________________________________
    And the query I am using:
    SELECT --TXR.TX_ID,
    TXR.TX_DATE, TXR.ITEM_ID,
    TO_CHAR(TRUNC((MIN(TXR.REAL_TIME) KEEP (DENSE_RANK FIRST ORDER BY TXR.REAL_TIME) )/3600),'FM00')||':'||TO_CHAR(TRUNC(MOD(MIN(TXR.REAL_TIME) KEEP (DENSE_RANK FIRST ORDER BY TXR.REAL_TIME) ,3600)/60),'FM00')||':'||TO_CHAR(MOD(MIN(TXR.REAL_TIME) KEEP (DENSE_RANK FIRST ORDER BY TXR.REAL_TIME) ,60),'FM00')||':'||TO_CHAR(MOD(MIN(TXR.REAL_TIME_FRAME) KEEP (DENSE_RANK FIRST ORDER BY TXR.REAL_TIME) ,60),'FM00') "AS RUN TIME",
    to_char(trunc((MAX(TXR.REAL_TIME+TXR.DURATION)-MIN(TXR.REAL_TIME))/3600),'FM00')||':'||to_char(trunc(mod(MAX(TXR.REAL_TIME+TXR.DURATION)-MIN(TXR.REAL_TIME),3600)/60),'FM00')||':'||to_char(mod(MAX(TXR.REAL_TIME+TXR.DURATION)-MIN(TXR.REAL_TIME),60),'FM00')||':'||to_char(mod(MAX(TXR.REAL_TIME_FRAME+TXR.DURATION_FRAME)-MIN(TXR.REAL_TIME),60),'FM00') "AS RUN DURATION",
    TO_CHAR(TRUNC((MIN(TXS.SCHEDULE_TIME) KEEP (DENSE_RANK FIRST ORDER BY TXR.REAL_TIME) )/3600),'FM00')||':'||TO_CHAR(TRUNC(MOD(MIN(TXS.SCHEDULE_TIME) KEEP (DENSE_RANK FIRST ORDER BY TXR.REAL_TIME) ,3600)/60),'FM00')||':'||TO_CHAR(MOD(MIN(TXS.SCHEDULE_TIME) KEEP (DENSE_RANK FIRST ORDER BY TXR.REAL_TIME) ,60),'FM00')||':'||TO_CHAR(MOD(MIN(TXS.SCHEDULE_TIME_FRAME) KEEP (DENSE_RANK FIRST ORDER BY TXR.REAL_TIME) ,60),'FM00') "SCHEDULED TIME",
    to_char(trunc((MAX(TXS.SCHEDULE_TIME+TXS.DURATION)-MIN(TXS.SCHEDULE_TIME))/3600),'FM00')||':'||to_char(trunc(mod(MAX(TXS.SCHEDULE_TIME+TXS.DURATION)-MIN(TXS.SCHEDULE_TIME),3600)/60),'FM00')||':'||to_char(mod(MAX(TXS.SCHEDULE_TIME+TXS.DURATION)-MIN(TXS.SCHEDULE_TIME),60),'FM00')||':'||to_char(mod(MAX(TXS.DURATION_FRAME),60),'FM00') "SCHEDULED DURATION"
    FROM TX_RECON_INSTANCE_VIEW TXR, TX_SCHEDULE TXS, TX_SCHEDULE_RECON TXREC
    WHERE TXR.TX_DATE=20100926 AND TXR.TX_TYPE='P'
    AND TXR.TX_ID=TXREC.RECON_TX_ID(+)
    AND TXREC.BASE_TX_ID=TXS.TX_ID(+)
    GROUP BY TXR.TX_DATE, TXR.ITEM_ID
    ORDER BY TXR.TX_DATE, TXR.ITEM_ID, MAX(TXR.REAL_TIME)--does this work for everyone now? let me know...thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Need help to redesign legacy SQL Script

    Hello Experts,
    I have the below code which produces a CREATE TRIGGER statement. as of now this does for updating. I need to re-design this code to add for inserting and deleting as well. I just need help in the structuring wise. I can build the logic for inserting and updating inside. I want to know how i can continue to get for "inserting" and "deleting" as well.
    you will understand my question better if you go through main code, present output and required output format below.
    I know this is a bad design first of all. but the below code is a legacy one. so i cant change the entire structure of the code :-( all i can do is to continue designing it to add new changes. Hence sought help from you all.
    please help
    SQL CODE:
    WITH audit_tables
    AS
       (SELECT object_name,
               MIN (column_id) min_col,
               MAX (column_id) max_col
        FROM   user_objects o,
               user_tab_columns c
        WHERE  o.object_name = 'CHR_VAL_DESC_A_T'
        AND    o.object_name = c.table_name
        GROUP BY object_name
    SELECT txt
    FROM (
    SELECT ' CREATE OR REPLACE TRIGGER ' || REPLACE(object_name,'_A_T') || '_ADT_TRG' || CHR(13) ||
           '   AFTER INSERT ' || CHR(13) ||
           '   OR    UPDATE ' || CHR(13) ||
           '   OR    DELETE ' || CHR(13) ||
           '   ON ' || REPLACE(object_name,'_A_T','_T') || CHR(13) ||
           '   FOR EACH ROW ' || CHR(13) ||
           ' DECLARE ' || CHR(13) ||
           ' BEGIN ' || CHR(13) ||
           ' IF updating THEN ' || CHR(13) ||
           '   INSERT INTO ' || object_name || CHR(13) ||
           '   (' txt, object_name, 1 disp_order, 0 column_id
    FROM audit_tables
    UNION ALL
    SELECT txt, object_name, disp_order, column_id
    FROM (SELECT 
            CASE
              WHEN max_col = column_id THEN
                '    '||column_name
              ELSE
                '    '||column_name || ','
              END AS txt, object_name, 2 disp_order, column_id
          FROM  audit_tables t,
                user_tab_columns C
          WHERE c.table_name = t.object_name
          ORDER BY c.column_id ASC)
    UNION ALL
    SELECT '   )' || CHR(13) ||
           '   VALUES ' || CHR(13) ||
           '   (', object_name, 3 disp_order, 0
    FROM audit_tables t
    UNION ALL
    SELECT txt, object_name, disp_order, column_id
    FROM (SELECT
            CASE
              WHEN max_col = column_id THEN
                CASE
                  WHEN SUBSTR(column_name,1,2) = 'N_' THEN
                    '    :NEW.'||decode(substr(column_name,1,2),'N_',substr(column_name,3))||');'
                  WHEN SUBSTR(column_name,1,2) = 'O_' THEN
                    '    :OLD.'||decode(substr(column_name,1,2),'O_',substr(column_name,3))||');'
                  WHEN min_col = column_id THEN
                    '    1'
                  WHEN column_id = 2 THEN
                    '     ''I'''
                  WHEN column_id = 3 THEN
                    '    SYSDATE'
                  ELSE
                  '    :NEW.'||column_name||');'
                END
              ELSE
                CASE
                  WHEN SUBSTR(column_name,1,2) = 'N_' THEN
                    '    :NEW.'||decode(substr(column_name,1,2),'N_',substr(column_name,3))||','
                  WHEN SUBSTR(column_name,1,2) = 'O_' THEN
                    '    :OLD.'||decode(substr(column_name,1,2),'O_',substr(column_name,3))||','
                  WHEN min_col = column_id THEN
                    '    1'||','
                  WHEN column_id = 2 THEN
                    '    ''I'''||','
                  WHEN column_id = 3 THEN
                    '    SYSDATE' ||','
                  ELSE
                    '    :NEW.'||column_name||','
                   END
              END AS txt,object_name, 4 disp_order, column_id
          FROM audit_tables t,
               user_tab_columns c
          WHERE c.table_name = t.object_name
          ORDER BY c.column_id ASC)
    UNION ALL
    SELECT 'END '||REPLACE(object_name,'_A_T') || '_ADT_TRG;' || CHR(13),
           object_name, 5 disp_order, 0
    FROM    audit_tables)
    ORDER BY object_name, disp_order, column_id
    PRESENT OUTPUT:
    CREATE OR REPLACE TRIGGER CHR_VAL_DESC_ADT_TRG
       AFTER INSERT
       OR    UPDATE
       OR    DELETE
       ON CHR_VAL_DESC_T
       FOR EACH ROW
    DECLARE
    BEGIN
    IF updating THEN
       INSERT INTO CHR_VAL_DESC_A_T
        TXN_ID,                                  
        TXN_TYP,                                 
        ADT_DTTM,                                
        CHR_VAL_DESC_ID,                         
        CHR_VAL_ID,                              
        LANG_ID,                                 
        DESC_ID,                                 
        O_CHR_VAL_DESC,                          
        N_CHR_VAL_DESC,                          
        O_TRANS_STATE,                           
        N_TRANS_STATE,                           
        CRTD_BY,                                 
        CRTD_DTTM,                               
        O_UPD_BY,                                
        N_UPD_BY,                                
        O_UPD_DTTM,                              
        N_UPD_DTTM,                              
        O_LOCK_NUM,                              
        N_LOCK_NUM                               
       VALUES
        1,                                       
        'I',                                     
        SYSDATE,                                 
        :NEW.CHR_VAL_DESC_ID,                    
        :NEW.CHR_VAL_ID,                         
        :NEW.LANG_ID,                            
        :NEW.DESC_ID,                            
        :OLD.CHR_VAL_DESC,                       
        :NEW.CHR_VAL_DESC,                       
        :OLD.TRANS_STATE,                        
        :NEW.TRANS_STATE,                        
        :NEW.CRTD_BY,                            
        :NEW.CRTD_DTTM,                          
        :OLD.UPD_BY,                             
        :NEW.UPD_BY,                             
        :OLD.UPD_DTTM,                           
        :NEW.UPD_DTTM,                           
        :OLD.LOCK_NUM,                           
        :NEW.LOCK_NUM);                          
    END CHR_VAL_DESC_ADT_TRG;
    REQUIRED OUTPUT FORMAT:
    CREATE OR REPLACE TRIGGER TRIGGER_NAME
       AFTER INSERT
       OR    UPDATE
       OR    DELETE
       ON TABLE_NAME
       FOR EACH ROW
    DECLARE
    BEGIN
    IF updating THEN
       INSERT TABLE_NAME
        list of column names                               
       VALUES
    IF inserting THEN
       INSERT TABLE_NAME
        list of column names                               
       VALUES
    IF deleting THEN
       INSERT TABLE_NAME
        list of column names                               
       VALUES
    END TRIGGER_NAME;

    can anyone please help?
    i tried adding with inserting and updating also..but when i tried to add deleting part the final output not comes in proper structure.
    WITH audit_tables
    AS
       (SELECT object_name,
               MIN (column_id) min_col,
               MAX (column_id) max_col
        FROM   user_objects o,
               user_tab_columns c
        WHERE  o.object_name IN ('CHR_VAL_DESC_A_T', 'CHR_VAL_A_T')
        AND    o.object_name = c.table_name
        GROUP BY object_name
    SELECT txt
    FROM (
    SELECT ' CREATE OR REPLACE TRIGGER ' || REPLACE(object_name,'_A_T') || '_ADT_TRG' || CHR(13) ||
           '   AFTER INSERT ' || CHR(13) ||
           '   OR    UPDATE ' || CHR(13) ||
           '   OR    DELETE ' || CHR(13) ||
           '   ON ' || REPLACE(object_name,'_A_T','_T') || CHR(13) ||
           '   FOR EACH ROW ' || CHR(13) ||
           ' DECLARE ' || CHR(13) ||
           ' BEGIN ' || CHR(13) ||
           *' IF inserting THEN '* || CHR(13) ||
           '   INSERT INTO ' || object_name || CHR(13) ||
           '   (' txt, object_name, 1 disp_order, 0 column_id
    FROM audit_tables
    UNION ALL
    SELECT txt, object_name, disp_order, column_id
    FROM (SELECT 
            CASE
              WHEN max_col = column_id THEN
                '    '||column_name
              ELSE
                '    '||column_name || ','
              END AS txt, object_name, 2 disp_order, column_id
          FROM  audit_tables t,
                user_tab_columns C
          WHERE c.table_name = t.object_name
          ORDER BY c.column_id ASC)
    UNION ALL
    SELECT '   )' || CHR(13) ||
           '   VALUES ' || CHR(13) ||
           '   (', object_name, 3 disp_order, 0
    FROM audit_tables t
    UNION ALL
    SELECT txt, object_name, disp_order, column_id
    FROM (SELECT
            CASE
              WHEN max_col = column_id THEN
                CASE
                  WHEN SUBSTR(column_name,1,2) = 'N_' THEN
                    '    :NEW.'||decode(substr(column_name,1,2),'N_',substr(column_name,3))||');'
                  WHEN SUBSTR(column_name,1,2) = 'O_' THEN
                    '    NULL'||');'
                  WHEN min_col = column_id THEN
                    '    1'
                  WHEN column_id = 2 THEN
                    '     ''I'''
                  WHEN column_id = 3 THEN
                    '    SYSDATE'
                  ELSE
                  '    :NEW.'||column_name||');'
                END
              ELSE
                CASE
                  WHEN SUBSTR(column_name,1,2) = 'N_' THEN
                    '    :NEW.'||decode(substr(column_name,1,2),'N_',substr(column_name,3))||','
                  WHEN SUBSTR(column_name,1,2) = 'O_' THEN
                    '    NULL'||','
                  WHEN min_col = column_id THEN
                    '    1'||','
                  WHEN column_id = 2 THEN
                    '    ''I'''||','
                  WHEN column_id = 3 THEN
                    '    SYSDATE' ||','
                  ELSE
                    '    :NEW.'||column_name||','
                   END
              END AS txt,object_name, 4 disp_order, column_id
          FROM audit_tables t,
               user_tab_columns c
          WHERE c.table_name = t.object_name
          ORDER BY c.column_id ASC)
    UNION ALL
    SELECT txt, object_name, disp_order, column_id
    FROM(SELECT *' ELSIF updating THEN '* || CHR(13) ||
           '   INSERT INTO ' || object_name || CHR(13) ||
           '   (' txt, object_name, 5 disp_order, 0 column_id
    FROM audit_tables
    UNION ALL
    SELECT txt, object_name, disp_order, column_id
    FROM (SELECT 
            CASE
              WHEN max_col = column_id THEN
                '    '||column_name
              ELSE
                '    '||column_name || ','
              END AS txt, object_name, 6 disp_order, column_id
          FROM  audit_tables t,
                user_tab_columns C
          WHERE c.table_name = t.object_name
          ORDER BY c.column_id ASC)
    UNION ALL
    SELECT '   )' || CHR(13) ||
           '   VALUES ' || CHR(13) ||
           '   (', object_name, 7 disp_order, 0
    FROM audit_tables t
    UNION ALL
    SELECT txt, object_name, disp_order, column_id
    FROM (SELECT
            CASE
             WHEN max_col = column_id THEN
                CASE
                  WHEN SUBSTR(column_name,1,2) = 'N_' THEN
                    '    :NEW.'||decode(substr(column_name,1,2),'N_',substr(column_name,3))||');'
                  WHEN SUBSTR(column_name,1,2) = 'O_' THEN
                    '    :OLD.'||decode(substr(column_name,1,2),'O_',substr(column_name,3))||');'
                  WHEN min_col = column_id THEN
                    '    1'
                  WHEN column_id = 2 THEN
                    '     ''U'''
                  WHEN column_id = 3 THEN
                    '    SYSDATE'
                  ELSE
                  '    :NEW.'||column_name||');'
                END
              ELSE
                CASE
                  WHEN SUBSTR(column_name,1,2) = 'N_' THEN
                    '    :NEW.'||decode(substr(column_name,1,2),'N_',substr(column_name,3))||','
                  WHEN SUBSTR(column_name,1,2) = 'O_' THEN
                    '    :OLD.'||decode(substr(column_name,1,2),'O_',substr(column_name,3))||','
                  WHEN min_col = column_id THEN
                    '    1'||','
                  WHEN column_id = 2 THEN
                    '    ''U'''||','
                  WHEN column_id = 3 THEN
                    '    SYSDATE' ||','
                  ELSE
                    '    :NEW.'||column_name||','
                END
              END AS txt,object_name, 8 disp_order, column_id
          FROM audit_tables t,
               user_tab_columns c
          WHERE c.table_name = t.object_name
          ORDER BY c.column_id ASC)
    UNION ALL
    SELECT 'END IF;' || CHR(13) ||
           'END '||REPLACE(object_name,'_A_T') || '_ADT_TRG;' || CHR(13),
           object_name, 9 disp_order, 0
    FROM    audit_tables)
    ORDER BY object_name, disp_order, column_id)

  • Help to write an sql query

    Hi everyone!
    I need some help in composing a query that would calculate the number of occurrences of '29-Feb' between 2 given dates (i.e. substitution variables).
    What I figured so far is a way too complex and don't work all the time. Also I do know, that calculating a leap year is a bit different than just year mod 4 = 0.
    I would appreciate very much if you help me to write this query or just give me a guess.
    SELECT TO_NUMBER(TO_CHAR(date2, 'YYYY')-TO_CHAR(date1, 'YYYY'))/4
    FROM
    (SELECT CASE
    WHEN MOD(TO_NUMBER(TO_CHAR(TO_DATE('&&date1', 'DD-Mon-RR'), 'RR')), 4) = 0
    THEN TO_DATE('&date1', 'DD-Mon-RR')
    ELSE(CASE
    WHEN MOD(TO_NUMBER(TO_CHAR(ADD_MONTHS(TO_DATE('&date1', 'DD-Mon-RR'), 12), 'RR')), 4) = 0
    THEN ADD_MONTHS(TO_DATE('&date1', 'DD-Mon-RR'), 12)
    ELSE(CASE
    WHEN MOD(TO_NUMBER(TO_CHAR(ADD_MONTHS(TO_DATE('&date1', 'DD-Mon-RR'), 24), 'RR')), 4) = 0
    THEN ADD_MONTHS(TO_DATE('&date1', 'DD-Mon-RR'), 24)
    ELSE(CASE
    WHEN MOD(TO_NUMBER(TO_CHAR(ADD_MONTHS(TO_DATE('&date1', 'DD-Mon-RR'), 12), 'RR')), 4) = 0
    THEN ADD_MONTHS(TO_DATE('&date1', 'DD-Mon-RR'), 36)
    END)
    END)
    END)
    END date1,
    CASE
    WHEN MOD(TO_NUMBER(TO_CHAR(TO_DATE('&&date2', 'DD-Mon-RR'), 'RR')), 4) = 0
    THEN TO_DATE('&date2', 'DD-Mon-RR')
    ELSE(CASE
    WHEN MOD(TO_NUMBER(TO_CHAR(ADD_MONTHS(TO_DATE('&date2', 'DD-Mon-RR'), 12), 'RR')), 4) = 0
    THEN ADD_MONTHS(TO_DATE('&date2', 'DD-Mon-RR'), 12)
    ELSE(CASE
    WHEN MOD(TO_NUMBER(TO_CHAR(ADD_MONTHS(TO_DATE('&date2', 'DD-Mon-RR'), 24), 'RR')), 4) = 0
    THEN ADD_MONTHS(TO_DATE('&date2', 'DD-Mon-RR'), 24)
    ELSE(CASE
    WHEN MOD(TO_NUMBER(TO_CHAR(ADD_MONTHS(TO_DATE('&date2', 'DD-Mon-RR'), 12), 'RR')), 4) = 0
    THEN ADD_MONTHS(TO_DATE('&date2', 'DD-Mon-RR'), 36)
    END)
    END)
    END)
    END date2
    FROM DUAL);
    UNDEFINE date1;
    UNDEFINE date2;

    Hi,
    Interesting problem!
    The query below looks at the 59th day after January 1 in each year.
    If that date was in February, then it was a leap year.
    If that date was not in February, then it was a common year.
    DEFINE     date1     = "TO_DATE ('07-11-1609', 'DD-MM-YYYY')"
    DEFINE     date2     = "TO_DATE ('06-11-2009', 'DD-MM-YYYY')"
    WITH     all_years AS
         SELECT     ADD_MONTHS ( TRUNC (&date1, 'YYYY')
                      , 12 * (LEVEL - 1)
                      ) + 59       AS dt
         FROM     dual
         CONNECT BY     LEVEL <= 1 + CEIL ( MONTHS_BETWEEN ( &date2
                                                         , &date1
                               / 12
    SELECT     COUNT ( CASE
                   WHEN  TO_CHAR (dt, 'MM') = '02'
                   THEN  1
              END
               )          AS leap_year_cnt
    FROM     all_years
    WHERE     dt     BETWEEN      &date1
              AND      &date2
    ;A less efficient (for what that's worth) way is to generate all dates between &date1 and &date2, and test each one to see if it is '02-29'.
    I'll leave that as an exercise to the reader.
    HINT: the coding is simpler than the query above. (In my prolix style, it took 10 lines. No sub-query is needed.)

Maybe you are looking for

  • Photos and movies don't appear in Events/Photos but do appear in Last 12 months

    Hello. I'm using the latest version of iPhoto 11 (9.1.1). When I browse through my photos via the Events or Photos section of the iPhoto sidebar (under Library), certain photos and movies are missing. They simply don't appear there at all. However, w

  • Looking for a printer to print from iPad. I like canon. I have iOS 5.0.1

    Looking for a printer to print from IPad. I like canon. I have iOS 5.0.1. What are people using.

  • Wireless issues after kernel update

    Hi, after I updated my kernel yesterday, I've been having some issues with my wireless. I'm on a dell inspiron 1545, using kde and I use the broadcom-wl driver form the AUR. Anyways. After I did a system update yesterday, it would refuse to load the

  • CMIR Common Distribution Channel

    Hi I have a few distribution channels e.g. 10 20 30 I have a few divisions e.g. 01 02 03 Now suppose I make 10 as the common distribution channel. My Sales area are defined as 1000/10/01 1000/20/02 1000/30/03 I create a customer master with the follo

  • User exit asking for access key in CMOD

    Hi Experts, I am trying to write source code for an user exit in CMOD by creating a project and assigning enhancement to it. When i click on user exit and press change it asks for access key . Can you please tell me if there is any other way to write