Help with a SQL statement...

Hello...

I have tried to find a way to write a SQL statement and may not seem to produce something that works. What I need is a set of results that returns each month that a given task is in an open State. The only columns that I have in my work table with are TASK_NM, OPEN_DT and CLOSED_DT.

So if I have a line containing the following: TASK_NM = 'task one', OPEN_DT = April 18, 10 ' and CLOSED_DT = 14 October 10 '... I would like to see as a result set that looks like:

TASK_NM YEAR JAN FEB MAR APR MAY JUNE JULY AUG SEP OCT NOV DEC
the task of a 2010 0 0 0 1 1 1 1 1 1 1 0 0

Is it still possible?

Thanks in advance,
David.

Published by: user13027968 on March 10, 2011 14:19

Published by: user13027968 on March 10, 2011 15:13

Hello

Welcome to the Forum!

Whenever you have a question. Please post a small example of data (CREATE TABLE and INSERT statements) and the results desired from these data.
For example, the sample data may be:

CREATE TABLE     table_x
(       task_nm          VARCHAR2 (10)
,     open_dt          DATE
,     closed_dt     DATE
);

INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('task a', DATE '2010-04-18', DATE '2010-10-14');
INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('foo',    DATE '2010-10-31', DATE '2011-01-01');
INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('foo',    DATE '2010-12-01', DATE '2011-02-21');
INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('foo',    DATE '2011-04-01', DATE '2011-04-30');
INSERT INTO table_x (task_nm, open_dt, closed_dt) VALUES ('bar',    DATE '2010-01-01', DATE '2010-01-01');

From this data, you may want these results:

TASK_NM     YEAR JAN FEB MAR APR MAY JUN JUL AUG SEP OVT NOV DEC
---------- ----- --- --- --- --- --- --- --- --- --- --- --- ---
bar         2010   1   0   0   0   0   0   0   0   0   0   0   0
foo         2010   0   0   0   0   0   0   0   0   0   1   1   1
foo         2011   1   1   0   1   0   0   0   0   0   0   0   0
task a      2010   0   0   0   1   1   1   1   1   1   1   0   0

I'm not sure eactly how you plan to use it. Are there lines that overlap for the name of the task? You always want the same number of columns? What version of Oracle are you using?
I think you want something like this:

WITH     got_month_cnt          AS
(
     SELECT  task_nm
     ,     TRUNC (open_dt, 'MONTH')     AS first_month
     ,     1 + MONTHS_BETWEEN ( TRUNC (closed_dt, 'MONTH')
                         , TRUNC (open_dt,   'MONTH')
                       )          AS month_cnt
     FROM    table_x
--     WHERE     ...     -- If you want any filtering, put it here
)
,     cntr     AS
(
     SELECT     LEVEL     AS n
     FROM     (
               SELECT  MAX (month_cnt)     AS max_month_cnt
               FROM     got_month_cnt
          )
     CONNECT BY     LEVEL     <= max_month_cnt
)
,     all_months     AS
(
     SELECT     m.task_nm
     ,     ADD_MONTHS ( m.first_month
                  , c.n - 1
                  )          AS open_month
     FROM     got_month_cnt     m
     JOIN     cntr          c  ON     c.n     <= m.month_cnt
)
SELECT       task_nm
,       EXTRACT (YEAR FROM open_month)                         AS year
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jan' THEN 1 ELSE 0 END)     AS jan
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Feb' THEN 1 ELSE 0 END)     AS feb
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Mar' THEN 1 ELSE 0 END)     AS mar
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Apr' THEN 1 ELSE 0 END)     AS apr
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'May' THEN 1 ELSE 0 END)     AS may
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jun' THEN 1 ELSE 0 END)     AS jun
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jul' THEN 1 ELSE 0 END)     AS jul
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Aug' THEN 1 ELSE 0 END)     AS aug
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Sep' THEN 1 ELSE 0 END)     AS sep
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Oct' THEN 1 ELSE 0 END)     AS ovt
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Nov' THEN 1 ELSE 0 END)     AS nov
,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Dec' THEN 1 ELSE 0 END)     AS dec
FROM       all_months
GROUP BY  task_nm
,       EXTRACT (YEAR FROM open_month)
ORDER BY  task_nm
,            year
;

This will work in Orfacle 9 (and), but from Oracle 11, you could simplify it a little bit by using SELECT... Function PIVOT.

Published by: Frank Kulash, March 10, 2011 16:51

Tags: Database

Similar Questions

  • Help with making SQL query references to column aliases in the Case statement

    I need help with a sql query that I'm trying. I can go about it the wrong way, but I would be grateful if I could get any suggestions on possible solutions. This is my query:


    SELECT DISTINCT spriden_pidm, spriden_id id, spriden_last_name | ',' | spriden_first_name name,

    CASE
    WHEN rcresar_comm_code_01 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_01
    WHEN rcresar_comm_code_02 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_02
    WHEN rcresar_comm_code_03 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_03
    WHEN rcresar_comm_code_04 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_04
    WHEN rcresar_comm_code_05 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_05
    WHEN rcresar_comm_code_06 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_06
    WHEN rcresar_comm_code_07 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_07
    WHEN rcresar_comm_code_08 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_08
    WHEN rcresar_comm_code_09 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_09
    WHEN rcresar_comm_code_10 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_10
    END acg_elig_comm_code

    CASE
    WHEN acg_elig_comm_code = ' 268' THEN 'rigorous HS course. "
    WHEN acg_elig_comm_code = '269' THEN ' 2 or several AP or IB"
    WHEN acg_elig_comm_code = '270' THEN 'NOC as possible ".
    END comm_code_description

    OF spriden, rcresar, rcrapp1

    WHERE (rcresar_comm_code_01 IN ('268 ', '269', ' 270')

    OR rcresar_comm_code_02 ('268 ', '269', ' 270')

    OR rcresar_comm_code_03 ('268 ', '269', ' 270')

    OR rcresar_comm_code_04 ('268 ', '269', ' 270')

    OR rcresar_comm_code_05 ('268 ', '269', ' 270')

    OR rcresar_comm_code_06 ('268 ', '269', ' 270')

    OR rcresar_comm_code_07 ('268 ', '269', ' 270')

    OR rcresar_comm_code_08 ('268 ', '269', ' 270')

    OR rcresar_comm_code_09 ('268 ', '269', ' 270')

    OR rcresar_comm_code_10 ('268 ', '269', ' 270'))


    Rcresar_aidy_code = & aidy_code

    AND rcrapp1_aidy_code = rcresar_aidy_code

    AND rcrapp1_curr_rec_ind = 'Y '.

    AND rcrapp1_seq_no = rcresar_seq_no


    AND spriden_pidm = rcresar_pidm

    AND rcrapp1_pidm = rcresar_pidm


    AND spriden_change_ind IS NULL

    ORDER BY name


    The second case statement is where I don't know exactly what it takes to get what I want.

    Output should be like:
    spriden_pidm name ID acg_elig_comm_code comm_code_description
    «0000000000', ' 1111111111 ","John Doe","268", «rigorous HS race"»

    If I take the second case statement it works great except that I do not have my comm_code description column. My question is how can I use my first statement value box to determine this column? I think that I need a case statement as I have, but I don't know how to reference the value of acg_elig_comm_code. Any help would be greatly appreciated. Thank you.

    Published by: blackhole82 on January 20, 2009 09:20

    Hello

    You cannot use the alias column in the query, even where it is set (except in the ORDER BY clause).
    You can set the alias in a subquery and then use it in a great query, like this:

    WITH  sub_q  AS
    (
        SELECT DISTINCT spriden_pidm,spriden_id id, spriden_last_name||', '||spriden_first_name name,
            CASE
                WHEN rcresar_comm_code_01 IN ('268','269','270') THEN rcresar_comm_code_01
                WHEN rcresar_comm_code_02 IN ('268','269','270') THEN rcresar_comm_code_02
                WHEN rcresar_comm_code_03 IN ('268','269','270') THEN rcresar_comm_code_03
                WHEN rcresar_comm_code_04 IN ('268','269','270') THEN rcresar_comm_code_04
                WHEN rcresar_comm_code_05 IN ('268','269','270') THEN rcresar_comm_code_05
                WHEN rcresar_comm_code_06 IN ('268','269','270') THEN rcresar_comm_code_06
                WHEN rcresar_comm_code_07 IN ('268','269','270') THEN rcresar_comm_code_07
                WHEN rcresar_comm_code_08 IN ('268','269','270') THEN rcresar_comm_code_08
                WHEN rcresar_comm_code_09 IN ('268','269','270') THEN rcresar_comm_code_09
                WHEN rcresar_comm_code_10 IN ('268','269','270') THEN rcresar_comm_code_10
            END acg_elig_comm_code   -- Originally posted with , here (error)
        FROM spriden, rcresar, rcrapp1
        WHERE (rcresar_comm_code_01 IN ('268','269','270')
                OR rcresar_comm_code_02 IN ('268','269','270')
                OR rcresar_comm_code_03 IN ('268','269','270')
                OR rcresar_comm_code_04 IN ('268','269','270')
                OR rcresar_comm_code_05 IN ('268','269','270')
                OR rcresar_comm_code_06 IN ('268','269','270')
                OR rcresar_comm_code_07 IN ('268','269','270')
                OR rcresar_comm_code_08 IN ('268','269','270')
                OR rcresar_comm_code_09 IN ('268','269','270')
                OR rcresar_comm_code_10 IN ('268','269','270'))
        AND rcresar_aidy_code = &aidy_code
        AND rcrapp1_aidy_code = rcresar_aidy_code
        AND rcrapp1_curr_rec_ind = 'Y'
        AND rcrapp1_seq_no = rcresar_seq_no
        AND spriden_pidm = rcresar_pidm
        AND rcrapp1_pidm = rcresar_pidm
        AND spriden_change_ind IS NULL
    )
    SELECT    sub_q.*,
              CASE
                  WHEN acg_elig_comm_code = '268' THEN 'Rigorous HS course'
                  WHEN acg_elig_comm_code = '269' THEN '2 or more AP or IB'
                  WHEN acg_elig_comm_code = '270' THEN 'ACG possible'
              END comm_code_description
    FROM      sub_q
    ORDER BY  name
    

    Furthermore, you might think to rearrange your table, so that you do not have 10 columns (rcresar_comm_code_01, rcresar_comm_code_02,...) that essentially do the same thing. The usual way to handle this kind of one-to-many relationship is to have all rcresar_comm_codes in a separate table, one per line, with a pointer to the table where you have them now.

    Published by: Frank Kulash, January 20, 2009 11:35
    Syntax error has been corrected

  • Help with the insert statement

    Hello

    I was wondering if someone could help write me a sql statement.

    Here is my table:
    CREATE TABLE "TEMP_INVOICE" 
       ("INVOICE" VARCHAR2(100 BYTE),
         "DATE_OF_DOCUMENT" DATE, 
         "DATE_OF_PAY_DAY" DATE, 
         "D" NUMBER, 
         "K" NUMBER
       );
    Here are the instructions for correct insertion. This time, I posted 2 examples with 2 numbers different otherwise.
    insert into temp_invoice (invoice,DATE_OF_DOCUMENT,DATE_OF_PAY_DAY,d,k)  values (1000,to_date('01.02.2012','dd.mm.yyyy'),to_date('01.03.2012','dd.mm.yyyy'),5000,0);
     
    insert into temp_invoice (invoice,DATE_OF_DOCUMENT,DATE_OF_PAY_DAY,d,k)  values (1000,to_date('01.04.2012','dd.mm.yyyy'),'','',1000);
     
    insert into temp_invoice (invoice,DATE_OF_DOCUMENT,DATE_OF_PAY_DAY,d,k)  values (1000,to_date('01.05.2012','dd.mm.yyyy'),'','',3000);
     
    insert into temp_invoice (invoice,DATE_OF_DOCUMENT,DATE_OF_PAY_DAY,d,k)  values (1000,to_date('01.06.2012','dd.mm.yyyy'),'','',1000);
    
    insert into temp_invoice (invoice,DATE_OF_DOCUMENT,DATE_OF_PAY_DAY,d,k)  values (2000,to_date('01.07.2012','dd.mm.yyyy'),to_date('01.09.2012','dd.mm.yyyy'),8000,0);
     
    insert into temp_invoice (invoice,DATE_OF_DOCUMENT,DATE_OF_PAY_DAY,d,k)  values (2000,to_date('01.10.2012','dd.mm.yyyy'),'','',5000);
     
    insert into temp_invoice (invoice,DATE_OF_DOCUMENT,DATE_OF_PAY_DAY,d,k)  values (2000,to_date('01.11.2012','dd.mm.yyyy'),'','',2000);
     
    insert into temp_invoice (invoice,DATE_OF_DOCUMENT,DATE_OF_PAY_DAY,d,k)  values (2000,to_date('01.12.2012','dd.mm.yyyy'),'','',1000);
    I want to do is make an insert allows you to table another call is MADE:
    CREATE TABLE "INVOICE" 
       ("INVOICE" VARCHAR2(100 BYTE),
        "DATE_OF_DOCUMENT" DATE, 
         "DATE_OF_PAY_DAY" DATE,
         "DATE_OF_PAYMENT_REC" DATE,
         "VALUE" NUMBER,
         "VALUE_DEDUCT" NUMBER,
        "DATE_FROM" DATE,     
         "DATE_TO" DATE
         );
    Statements in the INVOICE table should be like this:


    ........ The Bill... date_of_document... date_of_pay_day... date_of_payment_rec... value... value_deduct... Date_from... Date_to
    1......     1000...............1.1.2012.................1.3.2012................NULL............................ 5000... NULL... 1.3.2012...1.4.2012
    2......     1000...............1.4.2012.................NULL..................... 1.4.2012...1000... 4000... 2.4.2012... 1.5.2012
    3......     1000...............1.5.2012.................NULL..................... 1.5.2012...3000... 1000... 2.5.2012... 1.6.2012
    4......     1000...............1.6.2012.................NULL..................... 1.6.2012...1000


    Can someone help me with the sql statement that would insert data from table to table Bill temp_invoice as in the example?

    Thank you!

    PS

    I would try to explain.
    (1) the first statement that is to be inserted is original imply that at which is different DATE_OF_PAY_DAY to NULL.
    To this inserted negative of the original imply, we must add date_from that is exatly the same date_of_pay_day and date_to which is exactly the same as the date of the first payment. Payment which came first!
    (2) we have now in the second insert statement. It will be the first payment of lease with date_of_document and date_pf_payment_rec, which is the same as date_fo_document. Value field will be populated with the amount of payment received and value_deduct field will be the value of the original imply - value of the first payment. Date is date_of_document + 1 and date_to is the date of the next payment.
    (3) Insert us the next installment. Date_od_payment_rec is the same as date_of_document... value is the amount of the second payment and value_deduct's previous value_deduct which was of 4000 - value of this second payment. date_from date_of_payment_rec + 1 and date_to is the date of the next payment

    So we continue this same pattern until we reached the final payment when we finish insert with the statement:
    Date of the document (date of the last payment received) and even for date_of_payment_rec and field value with the amount of the payment receieved. The rest (value_deduct, date_from, date_to) is null.

    I really hope you understand what I'm trying to do here.

    If you have any other questions please.

    Published by: user13071990 on November 22, 2012 04:16

    Published by: user13071990 on November 22, 2012 04:16

    Hello

    user13071990 wrote:
    ... Here are the instructions for correct insertion. This time, I posted 2 examples with 2 numbers different otherwise.

    Ok!
    Be sure to post the results you want new data.

    You probably need to add "PARTITION BY the Bill" to all analytical clauses in my solution:

    INSERT INTO invoice
    ( invoice, date_of_document, date_of_pay_day, date_of_payment_rec
    , value,   value_deduct,     date_from,           date_to
    )
    SELECT       invoice
    ,       date_of_document
    ,       date_of_pay_day
    ,       CASE
               WHEN  k > 0
               THEN  date_of_document
           END          AS date_of_payment_rec
    ,       NVL (d, k)     AS value
    ,       NVL2 ( date_of_pay_day
                , NULL
                , SUM (d) OVER ( PARTITION BY  invoice
                                          ORDER BY      date_of_document
                         )
                - SUM (k) OVER ( PARTITION BY  invoice
                                          ORDER BY      date_of_document
                         )
                )     AS value_deduct
    ,       NVL ( date_of_pay_day
               , date_of_document + 1
               )          AS date_from
    ,       LEAD (date_of_document) OVER ( PARTITION BY  invoice
                                            ORDER BY      date_of_document
                               )
                          AS date_to
    FROM       temp_invoice
    ;
    

    Because I'm not an English speaker nativ, that I just posted what it should look like after the insert is successful.

    OK, so you can't explain as you want, but you still need to explain.

    ... @Frank Kulash: you are very close, but still not quite what I'm looking for.

    Point out where my solution is the production of incorrect results, and explain (as you can) how to get good results in these places.

  • need help with the Update statement

    Hello
    I received a question in a course and I tried my best to respond, and now my brain is giving. I would really appreciate help with the update statement. I don't mind if you do not validate a solution, a little nudge in the right direction would be really useful. I'll post that I got.

    THE QUESTION
    / * For these agents disabled on more than seven missions, change their date of deactivation of the first date of deactivation of all the agents that have been activated in the same year as the agent that you update currently.
    */

    I have it divided into parts, here is my select statement to agents disabled on more than 7 missions, which produces the deactivation_dates in the agents table that I want to update...
    SELECT
    s.deactivation_date
    FROM
    (
    SELECT
    a.deactivation_date,
    count(m.mission_id) as nomissions
    FROM
    agents a
    INNER JOIN
    missions_agents m
    on
    a.agent_id=m.agent_id
    GROUP BY
    a.deactivation_date
    ) s
    WHERE
    s.nomissions>7 AND s.deactivation_date IS NOT NULL
    .. .and the code for the first date of deactivation for each year of activation agent
    select 
    a2.deactivation_date
    from
    agents a2
    where a2.deactivation_date= 
    (
    select min(a.deactivation_date)
    from 
    agents a
    where to_number(to_char(a.activation_date,'YYYY'))=to_number(to_char(a2.activation_date,'YYYY'))
    )
    ..... I am not real to marry these two statements together in the Update statement. I can't extract each date of deactivation produced in the first select statement and their match against the first date of deactivation in the year they have been activated for the second select statement.

    Any help greatly appreciated... :))

    I began to wonder how things would :)

    user8695469 wrote:
    First of all why he chooses the date the earliest of all agents

    UPDATE  AGENTS_COPY AC /* (1) */
    SET     DEACTIVATION_DATE = (
    SELECT  MIN(AGS.DEACTIVATION_DATE)
    FROM    AGENTS_COPY  AGS
    ,       AGENTS_COPY AC /* (2) */
    WHERE   TRUNC(AGS.ACTIVATION_DATE,'YEAR') = TRUNC(AC.ACTIVATION_DATE,'YEAR') /* (3) */
    )
    

    He recovers as soon as the subquery has not been correctly set in the SET clause. It seems you are trying to update a correlated, but we are still having a conceptual shift. I have added a few comments to your code above and below will explain.

    (1): when you do a correlated update it is useful to the table alias that you did right here.

    (2): this table statement is not necessary and is the reason why the FIRST deactivation date is selected. The alias that you use (3) refers to THIS table, not the one defined in the update statement. Remove the line indicated by (2) in the FROM clause and a correlated update will happen.

    and secondly why is it to update each row, when I thought that I'm just the lines where the agents are disabled and missions > 7? Pointers on where I'm wrong would be very appreciated. (SQL = stupid query language!) :)

    user8695469 wrote: then why is it to update each row, when I thought that I'm just the lines where the agents are disabled and missions > 7? Pointers on where I'm wrong would be very appreciated. (SQL = stupid query language!) :)

    
    WHERE EXISTS
    (
    SELECT
    a.agent_id,
    count(m.mission_id)
    FROM
    agents a
    /* INNER JOIN AC ON AC.AGENT_ID = A.AGENT_ID */
    INNER JOIN
    missions_agents m
    ON
    a.agent_id=m.agent_id
    GROUP BY
    a.agent_id,
    a.deactivation_date
    HAVING
    count(m.mission_id)>7 AND a.deactivation_date IS NOT NULL
    )
    

    Once again this problem is similar to the question above that a correlation update doesn't work. Test existence of lines in an EXISTS subquery. Since your subquery is not related to the table that you are trying to update, it will be always return a line and, therefore, it returns true for EACH LINE in the AGENTS table. To limit the game to only agents > 7 missions results, you need to add a join condition that references the table in your update statement. I added one above (with comments) as a sample.

    I recommend you look over all material that you have associated with correlated subqueries, including documents that I posted above. This seems to be what you're having the problem more with. If you need me to explain the concept of correlated queries any better please let me know.

    Thank you!

  • Need help with a SQL query

    Hello

    I have a data in table (raj_table) with columns (char11) raj_id, raj_number (varchar2 (15)), raj_format (NUMBER), Primary_ID (identity with the values of the primary key column)

    Primary_ID raj_id Raj_number Raj_format

    1                            raj                 rajvend                      1

    2                            raj                 rajvend                      1

    3                            raj                 rajvendor1                 2

    4                            raj                 rajvendor1                 2

    5                            raj                 rajvendor1                 2

    6                            raj                 rajvendor2                 3

    I used under SQL to get query output as below, but has not achieved the required result:

    Select client_id vendor_number, vendor_format, primary_id, row_number() on sl_no (client_id partition, primary_id, vendor_format order of client_id primary_id, vendor_format, vendor_number, vendor_number)

    from raj_table by sl_no asc

    SL_NO raj_id raj_number raj_format primary_id

    1                   1                   raj              rajvendor                 1

    1                   2                  raj              rajvendor                 1

    2                   3                   raj              rajvendor1                2

    2                   4                   raj              rajvendor1                2

    2                   5                  raj               rajvendor1                2

    3                   6                    raj              rajvendor2                3

    I need help with a SQL query to get the result as above without using the group by clause. I want to bring together the combination of separate line of the three columns (raj_id, raj_number, raj_format) and add a unique serial number for each online game (SL_NO column below). So, above there are 3 unique set of (raj_id, raj_number, raj_format) I can get in a group by clause, but I can not add prmiary_id, SL_NO values if I group by clause. I used the analytical functions like row_number() but no luck. Need solution for this.

    with t as)

    Select 'raj' raj_id, 'rajvend' raj_number, 1 raj_format, 1 primary_id Union double all the

    Select option 2, 'raj', 'rajvend', 1 double Union all

    Select 3, 'raj', 'rajvendor1', 2 double Union all

    Select 4, 'raj', 'rajvendor1', 2 double Union all

    Select 5, 'raj', 'rajvendor1', 2 double Union all

    Select 6, 'raj', 'rajvendor2', 3 double

    )

    Select dense_rank() over (order of raj_id, raj_number, raj_format) sl_no,

    t.*

    t

    order by primary_id

    /

    PRIMARY_ID RAJ RAJ_NUMBER RAJ_FORMAT SL_NO
    ---------- ---------- --- ---------- ----------
    1 1 raj rajvend 1
    1 2 raj rajvend 1
    2 3 raj rajvendor1 2
    2 4 raj rajvendor1 2
    2 5 raj rajvendor1 2
    3 6 raj rajvendor2 3

    6 selected lines.

    SQL >

    SY.

  • Help with oracle sql to get all possible combinations in a table.

    Hello guys I have a small predicatement which has me a little confused. I have a table similar to the following. (It is a sample of my real of the table. I use this to explain the original table containing sensitive data).
    CREATE TABLE TEST01( 
    TUID VARCHAR2(50),
    FUND VARCHAR2(50),
    ORG  VARCHAR2(50));
    Insert into TEST01 (TUID,FUND,ORG) values ('9102416AB','1XXXXX','6XXXXX');
    Insert into TEST01 (TUID,FUND,ORG) values ('9102416CC','100000','67130');
    Insert into TEST01 (TUID,FUND,ORG) values ('955542224','1500XX','67150');
    Insert into TEST01 (TUID,FUND,ORG) values ('915522211','1000XX','67XXX');
    Insert into TEST01 (TUID,FUND,ORG) values ('566653456','xxxxxx','xxxxx');
    "TUID"                        "FUND"                        "ORG"                         
    "9102416AB"                   "1XXXXX"                      "6XXXXX"                      
    "9102416CC"                   "100000"                      "67130"                       
    "955542224"                   "1500XX"                      "67150"                       
    "915522211"                   "1000XX"                      "67XXX"                       
    "566653456"                   "xxxxxx"                      "xxxxx"                       
    The 'X' is wildcard character elements * (I inherit it and I can not change the table format) * I would like to make a query as follows

    select tuid from test01 where fund= '100000' and org= '67130'
    However I like to do is to retrieve all the records that have have these segments in them including ' x
    in other words the output expected here would be

    "TUID"                        "FUND"                        "ORG"                         
    "9102416AB"                   "1XXXXX"                      "6XXXXX"                      
    "9102416CC"                   "100000"                      "67130"                       
    "915522211"                   "1000XX"                      "67XXX"                       
    "566653456"                   "xxxxxx"                      "xxxxx"  
    I started to write a massive sql statement that would have the 12 as the instruction inside, because I must compare the org and finance every possible way.
    This is where im headed. but im wondering if there is a better way.
    select * from test02
    where fund = '100000' and org = '67130'
    or fund like '1%' and org like '6%'
    or fund like '1%' and org like '67%'
    or fund like '1%' and org like '671%'
    or fund like '1%' and org like '6713%'
    or fund like '1%' and org like '67130'
    or fund like '10%' and org like '6%'...etc
    
    /*seems like there should be a better way..*/
    can someone give me a hand to come with this sql statement...

    mlov83 wrote:
    If I run the present

    select tuid,fund, org
    from   test01
    where '100000' like translate(fund, 'xX','%%') and '67130' like translate(org, 'xX','%%');
    

    That's what I

    "TUID"                        "FUND"                        "ORG"
    "9102416AB"                   "1XXXXX"                      "6XXXXX"
    "9102416CC"                   "100000"                      "67130"
    "915522211"                   "1000XX"                      "67XXX"
    "566653456"                   "xxxxxx"                      "xxxxx"
    "9148859fff"                  "1XXXXXX"                     "X6XXX"                       
    

    the last item should be excluded. The second digit in "org" is a "7".

    Fund is bad, too. Looking for 6 characters ("100000"), but the funds on this line is 7 characters ("1XXXXXX").

    and it's always get picked up.

    That's why you should use the Joker _ instead of %

    select  tuid, fund, org
    from    test01
    where  '100000' like translate (fund, 'xX', '__')
    and    '67130'  like translate (org,  'xX', '__')
    ;
    

    It is difficult to see, but in two calls to TRANSLATE, the 3rd argument is a string 2 ' _.

  • Need help with query SQL Inline views + Group

    Hello gurus,

    I would really appreciate your time and effort on this application. I have the following data set.

    Reference_No---Check_Number---Check_Date---description---Invoice_Number---Invoice_Type---Paid_Amount---Vendor_Number
    1234567 11223 - 05/07/2008 -paid for cleaning- 44345563-I-* 20.00 *---19
    1234567 11223 - 05/07/2008 - 44345563 -a--10,00---19 ofbad quality adjustment
    7654321 11223 - 05/07/2008 - setting the last billing cycle - 23543556 - A - 50.00 - 19
    4653456 11223 - 05/07/2008 - paid for cleaning - 35654765 - I - 30, 00-19

    Please ignore '-' added for clarity

    I'm writing a paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, aggregate query Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Type, Invoice_Number, Vendor_Number. When there are no more records I want to display the respective Description.

    The query should return the following data set

    Reference_No---Check_Number---Check_Date---description---Invoice_Number---Invoice_Type---Paid_Amount---Vendor_Number
    1234567 11223 - 05/07/2008 -paid for cleaning- 44345563-I-* 10.00 *---19
    7654321 11223 - 05/07/2008 - setting the last billing cycle - 23543556 - A - 50.00 - 19
    4653456 11223 - 05/07/2008 - paid for cleaning - 35654765 - I - 30, 00-19
    Here's my query. I'm a little lost.

    Select b., A.sequence_id, A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    de)
    Select sequence_id, check_number, check_date, invoice_number, sum (paid_amount) sum, vendor_number
    of the INVOICE
    Sequence_id group check_date, check_number, invoice_number, vendor_number
    ) A, B OF INVOICE
    where A.sequence_id = B.sequence_id


    Thank you
    Nick

    It seems that this is a duplicate thread - correct me if I am wrong in this case->

    Need help with query SQL Inline views + Group

    Kind regards.

    LOULOU.

  • Need help with PL/SQL so and then select

    Hello guys, I am new to the PL/SQl programming (only Java experience) and I'm pretty stuck to my task. It would be great if you could help me. I am in programming with Oracle SQL * Plus Version 10.2.0.3.0

    Whenever a user logs on to the server a database entry is created with information about the logged-on user. I need to create a PL/SQL command that selects all the information from last month. Unfortunately, the date_stamp column has a certain weird format: 1131210 for December 10, 2013


    My idea so far:


    DECLARE

    v_today NUMBER;

    BEGIN

    v_today: = TO_NUMBER (TO_CHAR (SYSDATE, 'MM'));       -Save the number of the month (e.g.12) in v_today

    IF v_today = 01 THEN

    SELECT * from audittrl

    WHERE the date_stamp between 1131201 AND the 1131231;

    ELSIF v_today = 02 THEN

    SELECT * from audittrl

    WHERE the date_stamp between the 1130131 AND 1130101;

    .......

    END IF;

    END;

    /

    Error code: "an INTO clause in this SELECT statement.

    I do not want to save the result to select a variable, hope you can help me. Thanks in advance.

    Hello

    6a4d1bcd-c00e-4dac-AB64-9b6bdb1652d1 wrote:

    Thanks, I'll try that, if still get caught once, I'll be back. Anway I'm not sure of the solution of Chris227, because I can't test it right now. From my point of view it gives you information the current month (e.g., December) and not the month previous (-online November), or have I missed something. ?

    You are right.  In addition, it does not for a given year.  If you have data from several years in the table, it will select lines for the month of December 2012, 2011, 2010,... but also of 2013.

    Here's a way to get around that:

    DECLARE

    prev_month_start PLS_INTEGER: = TO_NUMBER (TO_CHAR (ADD_MONTHS (SYSDATE-1)

    , "YYMM"1' "01"

    )

    );

    this_month_start PLS_INTEGER: = TO_NUMBER (TO_CHAR (SYSDATE

    , "YYMM"1' "01"

    )

    );

    BEGIN
    FOR (IN) rec
    SELECT *.
    Of audittrl
    WHERE the date_stamp > = prev_month_start
    AND date_stamp< >
    ORDER BY user_id, date_stamp - or other

    )
    LOOP
    dbms_output.put_line (rec.date_stamp);
    dbms_output.put_line (rec.event);
    dbms_output.put_line (rec.user_id)
    dbms_output.put_line (rec.host_name);
    END LOOP;
    END;

    This should also be more effective, because it will allow the optimizer to use an index on date_stamp.  Even if there is no index, it will be more effective because it avoids calling any function (for example, SUBSTR) on each line of the table.

    You needn't PL/SQL to get these results.  Just use SQL, you might say:

    SELECT event, host_name, user_id and date_stamp
    Of audittrl
    WHERE the date_stamp > = TO_NUMBER (TO_CHAR (ADD_MONTHS (SYSDATE-1)
    , "YYMM"1' "01"
    )
    )
    AND date_stamp<  to_number="" (="" to_char="" (="" sysdate="" to_number="" (="" to_char="" (="">


    , "YYMM"1' "01"
    )
    )

    ORDER BY user_id, date_stamp - or other

    ;

    Your front end will provide column headers and touch the data so that the columns line up.  It can also set the output to a file.  (For example, if your front-end is SQL * Plus, you can use the command of the COIL.)

    I guess date_stamp is a NUMBER.  If it is a string, the solutions above can be simplified a bit.

    This problem (and many other problems) would be so much simpler if date_stamp was a DATE column.  Using numbers or strings to store the date information is simply asking for trouble.

  • Need help with the insert statement

    Hello

    I have a question on how to write a SQL statement.

    This is the table of "base":
    CREATE TABLE TEMP_TBL
    (
    id_nr NUMBER,
    DATE_DOK DATE,
    DATE_DUE DATE,
    DATE_DOK_PAY DATE,
    DEB NUMBER,
    KRD NUMBER
    );
    
    insert into temp_tbl (ID_NR,DATE_DOK,DATE_DUE,DATE_DOK_PAY,DEB,KRD)values('1',TO_DATE('11.01.2011','DD.MM.YYYY'),TO_DATE('25.02.2011','DD.MM.YYYY'),NULL,'423,24','0');
    insert into temp_tbl(ID_NR,DATE_DOK,DATE_DUE,DATE_DOK_PAY,DEB,KRD)values('2',TO_DATE('16.12.2011','DD.MM.YYYY'),TO_DATE('13.06.2011','DD.MM.YYYY'),NULL,'91270,15','0');
    insert into temp_tbl(ID_NR,DATE_DOK,DATE_DUE,DATE_DOK_PAY,DEB,KRD)values('3',TO_DATE('27.09.2011','DD.MM.YYYY'),TO_DATE('27.09.2011','DD.MM.YYYY'),NULL,'0','2000');
    and it comes to resoult in the target table. SQL statement must take care of the insert in a base of the target table table (example below is already provided with test data).
    create table table_sod
    (
    
          id_nr number
         ,date_from date
         ,date_to date
         ,deb_krd number
    
    );
    
    One thing to note here :  values in column deb_krd under insert 1 and 4 must be summarized in insert 4.
    
    insert into table_sod (id_nr,date_from,date_to,deb_krd) values('1',null,to_date('25.02.2011','dd.mm.yyyy'),'423,24');
    insert into table_sod(id_nr,date_from,date_to,deb_krd) values('2',to_date('26.02.2011','dd.mm.yyyy'),to_date('13.06.2011','dd.mm.yyyy'),'423,24');
    insert into table_sod(id_nr,date_from,date_to,deb_krd)values('3',null,to_date('13.06.2011','dd.mm.yyyy'),'91270,15');
    insert into table_sod(id_nr,date_from,date_to,deb_krd)values('4',to_date('14.06.2011','dd.mm.yyyy')to_date('27.09.2011','dd.mm.yyyy'),'91693,39');
    insert into table_sod(id_nr,date_from,date_to,deb_krd)values('5',null,to_date('27.09.2011','dd.mm.yyyy'),'2000');
    If someone could give me a helping hand how write correct insert statement I would be really gratefull.

    Thank you for your time!

    I came here with my own assumptions with this

    SQL> select rownum id_nr
      2       , date_from
      3       , date_to
      4       , case when date_from is null then deb
      5              else sum(case when date_from is not null then deb else 0end) over(order by id_nr, no)
      6         end deb_krd
      7    from (
      8            select id_nr
      9                 , case when lg_dt is null or ld_dt = date_due then  null else lg_dt+1 end date_from
     10                 , ld_dt date_to
     11                 , case when deb = 0 then krd else deb end deb
     12                 , no
     13              from (
     14                      select t1.*
     15                           , lead(t1.date_due) over(order by t1.id_nr, t2.no) ld_dt
     16                           , lag(t1.date_due) over(order by t1.id_nr, t2.no) lg_dt
     17                           , t2.no
     18                        from temp_tbl t1
     19                       cross
     20                       join (select 1 no from dual union all select 2 no from dual) t2
     21                       order by id_nr, no
     22                   )
     23             where ld_dt is not null
     24         )
     25  /
    
         ID_NR DATE_FROM DATE_TO      DEB_KRD
    ---------- --------- --------- ----------
             1           25-FEB-11      42324
             2 26-FEB-11 13-JUN-11      42324
             3           13-JUN-11    9127015
             4 14-JUN-11 27-SEP-11    9169339
             5           27-SEP-11       2000
     
    
  • Date range of calculation with the SQL statement

    I'm sure that there is a way to do this in SQL, but I can't understand it. I can write a PL/SQL script to do it, but prefer to use a SQL statement. My database is the database of Oracle 10.2.0.4.0.

    I have a table that contains information such as employee number, service id, and date effective start-up of the person in this Department. There are data in another table I want to update their department number in based on their date of entry in the range. If I could figure out how to correctly select the entry into force, I can do the rest.

    I have data such as:
    EMP_ID DEPT_NO EFFECTIVE
    -------------- ----------------- ---------------------
    101 1000 1/15 / 2001
    1050 101 5/24 / 2005
    101 2010 6/8/2008
    101 1000 8/2/2010

    I want to write a SELECT statement that returns something like this where the end_date is the eve of the ENTRY into force and the last record didn't an end_date because they are always assigned to this service. In addition, the first record in the column, I won't choose a DEPT_NO because the logic of the entry into force has been added in January 2001, he says if a person started in 1985 they might have zero departments at several times so I won't update all data for this period:

    EMP_ID DEPT_NO EFFECTIVE END_DATE
    --------------- ---------------- ---------------- ----------------
    101 1/14 / 2001
    101 1000 1/15 / 2001 5/23/2005
    1050 101 5/24 / 2005 6/7/2008
    101 2010 6/8/2008-8/1/2010
    101 1000 8/2/2010

    Here is a script to create the data into a temporary table which can be used to write a SELECT statement. I added two records of employees with different dates.

    create the table temp_activity
    (emp_id number (12),)
    dept_no number (12).
    (entry into force);

    INSERT INTO temp_activity
    (EMP_ID, DEPT_NO, ENTERED INTO FORCE)
    VALUES
    (101,1000,to_date('1/15/2001','MM/DD/YYYY'))
    /
    INSERT INTO temp_activity
    (EMP_ID, DEPT_NO, ENTERED INTO FORCE)
    VALUES
    (101,1050,to_date('5/24/2005','MM/DD/YYYY'))
    /
    INSERT INTO temp_activity
    (EMP_ID, DEPT_NO, ENTERED INTO FORCE)
    VALUES
    (101,2010,to_date('6/8/2008','MM/DD/YYYY'))
    /
    INSERT INTO temp_activity
    (EMP_ID, DEPT_NO, ENTERED INTO FORCE)
    VALUES
    (101,1000,to_date('8/2/2010','MM/DD/YYYY'))
    /
    INSERT INTO temp_activity
    (EMP_ID, DEPT_NO, ENTERED INTO FORCE)
    VALUES
    (102,1040,to_date('1/15/2001','MM/DD/YYYY'))
    /
    INSERT INTO temp_activity
    (EMP_ID, DEPT_NO, ENTERED INTO FORCE)
    VALUES
    (102,2000,to_date('6/16/2006','MM/DD/YYYY'))
    /

    Any help is appreciated. It's probably easy, but I can't get my brain wrapped around it.

    Thanks - mike
    select  emp_id,
            dept_no,
            effective,
            end_date
      from  (
              select  emp_id,
                      dept_no,
                      effective,
                      lead(effective) over(partition by emp_id order by effective) - 1 end_date,
                      row_number() over(partition by emp_id order by effective) rn
                from  temp_activity
             union all
              select  emp_id,
                      null dept_no,
                      null effective,
                      min(effective) - 1 end_date,
                      0 rn
                from  temp_activity
                group by emp_id
            )
      order by emp_id,
               rn
    /
    
        EMP_ID    DEPT_NO EFFECTIVE  END_DATE
    ---------- ---------- ---------- ----------
           101                       01/14/2001
           101       1000 01/15/2001 05/23/2005
           101       1050 05/24/2005 06/07/2008
           101       2010 06/08/2008 08/01/2010
           101       1000 08/02/2010
           102                       01/14/2001
           102       1040 01/15/2001 06/15/2006
           102       2000 06/16/2006
    
    8 rows selected.
    
    SQL> 
    

    SY.

  • OSB: fn - bea: execute - sql () with the sql statement ' INSERT INTO...» »

    Dear Experts,

    I need a clarification. Is it possible to use the fn - bea: function execute sql (Oracle Service Bus) to perform an insert operation in a database with the data extracted from the message of the Organization (i.e. $body/Info/username)? If it is possible which is the right syntax?
    Any suggestion is appreciated.

    Kind regards
    Mike

    Published by: ITDeveloper on November 19, 2009 2.55

    Published by: ITDeveloper on November 19, 2009 3.01

    Hi Mike,.

    Please refer to my post for the same question to the fn - bea: sql performance with 'Insert INTO' the sql statement

    Thank you best regards &,.

    Vivek

  • Need help with PL/SQL query complex

    I need help with a query that need access to data from 3 tables. That's what I did

    I created 3 tables

    CREATE TABLE post_table
    (
    post_id varchar (20),
    datepost DATE,
    KEY (post_id) elementary SCHOOL
    ) ;

    CREATE TABLE topic
    (
    TOPIC_ID varchar (20),
    name varchar (20),
    PRIMARY KEY (topic_id)
    );

    CREATE TABLE blogpost_table
    (
    TOPIC_ID varchar (20),
    post_id varchar (20),
    PRIMARY KEY (topic_id, post_id);
    FOREIGN KEY (topic_id) REFERENCES topic (topic_id) ON DELETE CASCADE,
    FOREIGN KEY (post_id) REFERENCES post_table (post_id) ON DELETE CASCADE
    );


    Now, I inserted a few values in these tables as

    INSERT INTO post_table VALUES ('p1', to_date ('2009-09-14 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p2', to_date ('2009-07-18 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p3', to_date ('2009-07-11 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p4', to_date ('2009-03-11 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p5', to_date ('2009-07-13 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p6', to_date ('2009-06-12 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p7', to_date ('2009-07-11 18:00 "," MM/DD/YYYY mi:ss'));))

    INSERT INTO VALUES subject ("t1", "baseball");
    INSERT INTO category VALUES ('t2', 'football');

    INSERT INTO blogpost_table VALUES ("t1", "p1");
    INSERT INTO blogpost_table VALUES ('t1', 'p3');
    INSERT INTO blogpost_table VALUES ("t1", "p4");
    INSERT INTO blogpost_table VALUES ('t1', 'p5');
    INSERT INTO blogpost_table VALUES ('t2', 'p2');
    INSERT INTO blogpost_table VALUES ('t2', 'p6');
    INSERT INTO blogpost_table VALUES ("t2", "p7");


    I'm launching SQL queries on the table in this topic.

    I want to write a SQL query that returns me the name of a topic (s) and the number of blog_post (s) associated with the topic in descending order of the number of blog posts created in July.

    Can someone please help me to write this query?

    Thank you

    Published by: user11994430 on October 9, 2009 07:24

    Thanks for the test of the configuration!

    SQL>SELECT   t.NAME, COUNT(*)
      2      FROM topic t, blogpost_table b, post_table p
      3     WHERE b.topic_id = t.topic_id
      4       AND p.post_id = b.post_id
      5       AND p.datepost >= DATE '2009-07-01'
      6       AND p.datepost < DATE '2009-08-01'
      7  GROUP BY t.NAME
      8  ORDER BY COUNT(*) desc;
    
    NAME                   COUNT(*)
    -------------------- ----------
    baseball                      2
    soccer                        2
    

    HTH, Urs

  • I need help in the sql statement

    Hi all
    im working in the hr schema
    I need sql statement to answer my question
    I need information to all employees
    where average wage = average wage department 50
    Sorry I can't speak English very well
    I thank all

    There is no need to do so in the two motions. All you need is:

    select  *
      from  (
             select  e.*,
                     avg(case department_id when 50 then salary end) over() dept_50_avg_sal
               from  hr.employees e
            )
      where salary <= dept_50_avg_sal
    / 
    
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID DEPT_50_AVG_SAL
    ----------- -------------------- ------------------------- ------------------------- -------------------- --------- ---------- ---------- -------------- ---------- ------------- ---------------
            198 Donald               OConnell                  DOCONNEL                  650.507.9833         21-JUN-07 SH_CLERK         2600                       124            50      3475.55556
            199 Douglas              Grant                     DGRANT                    650.507.9844         13-JAN-08 SH_CLERK         2600                       124            50      3475.55556
            115 Alexander            Khoo                      AKHOO                     515.127.4562         18-MAY-03 PU_CLERK         3100                       114            30      3475.55556
            116 Shelli               Baida                     SBAIDA                    515.127.4563         24-DEC-05 PU_CLERK         2900                       114            30      3475.55556
            117 Sigal                Tobias                    STOBIAS                   515.127.4564         24-JUL-05 PU_CLERK         2800                       114            30      3475.55556
            118 Guy                  Himuro                    GHIMURO                   515.127.4565         15-NOV-06 PU_CLERK         2600                       114            30      3475.55556
            119 Karen                Colmenares                KCOLMENA                  515.127.4566         10-AUG-07 PU_CLERK         2500                       114            30      3475.55556
            125 Julia                Nayer                     JNAYER                    650.124.1214         16-JUL-05 ST_CLERK         3200                       120            50      3475.55556
            126 Irene                Mikkilineni               IMIKKILI                  650.124.1224         28-SEP-06 ST_CLERK         2700                       120            50      3475.55556
            127 James                Landry                    JLANDRY                   650.124.1334         14-JAN-07 ST_CLERK         2400                       120            50      3475.55556
            128 Steven               Markle                    SMARKLE                   650.124.1434         08-MAR-08 ST_CLERK         2200                       120            50      3475.55556
    
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID DEPT_50_AVG_SAL
    ----------- -------------------- ------------------------- ------------------------- -------------------- --------- ---------- ---------- -------------- ---------- ------------- ---------------
            129 Laura                Bissot                    LBISSOT                   650.124.5234         20-AUG-05 ST_CLERK         3300                       121            50      3475.55556
            130 Mozhe                Atkinson                  MATKINSO                  650.124.6234         30-OCT-05 ST_CLERK         2800                       121            50      3475.55556
            131 James                Marlow                    JAMRLOW                   650.124.7234         16-FEB-05 ST_CLERK         2500                       121            50      3475.55556
            132 TJ                   Olson                     TJOLSON                   650.124.8234         10-APR-07 ST_CLERK         2100                       121            50      3475.55556
            133 Jason                Mallin                    JMALLIN                   650.127.1934         14-JUN-04 ST_CLERK         3300                       122            50      3475.55556
            134 Michael              Rogers                    MROGERS                   650.127.1834         26-AUG-06 ST_CLERK         2900                       122            50      3475.55556
            135 Ki                   Gee                       KGEE                      650.127.1734         12-DEC-07 ST_CLERK         2400                       122            50      3475.55556
            136 Hazel                Philtanker                HPHILTAN                  650.127.1634         06-FEB-08 ST_CLERK         2200                       122            50      3475.55556
            138 Stephen              Stiles                    SSTILES                   650.121.2034         26-OCT-05 ST_CLERK         3200                       123            50      3475.55556
            139 John                 Seo                       JSEO                      650.121.2019         12-FEB-06 ST_CLERK         2700                       123            50      3475.55556
            140 Joshua               Patel                     JPATEL                    650.121.1834         06-APR-06 ST_CLERK         2500                       123            50      3475.55556
    
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID DEPT_50_AVG_SAL
    ----------- -------------------- ------------------------- ------------------------- -------------------- --------- ---------- ---------- -------------- ---------- ------------- ---------------
            142 Curtis               Davies                    CDAVIES                   650.121.2994         29-JAN-05 ST_CLERK         3100                       124            50      3475.55556
            143 Randall              Matos                     RMATOS                    650.121.2874         15-MAR-06 ST_CLERK         2600                       124            50      3475.55556
            144 Peter                Vargas                    PVARGAS                   650.121.2004         09-JUL-06 ST_CLERK         2500                       124            50      3475.55556
            180 Winston              Taylor                    WTAYLOR                   650.507.9876         24-JAN-06 SH_CLERK         3200                       120            50      3475.55556
            181 Jean                 Fleaur                    JFLEAUR                   650.507.9877         23-FEB-06 SH_CLERK         3100                       120            50      3475.55556
            182 Martha               Sullivan                  MSULLIVA                  650.507.9878         21-JUN-07 SH_CLERK         2500                       120            50      3475.55556
            183 Girard               Geoni                     GGEONI                    650.507.9879         03-FEB-08 SH_CLERK         2800                       120            50      3475.55556
            186 Julia                Dellinger                 JDELLING                  650.509.3876         24-JUN-06 SH_CLERK         3400                       121            50      3475.55556
            187 Anthony              Cabrio                    ACABRIO                   650.509.4876         07-FEB-07 SH_CLERK         3000                       121            50      3475.55556
            190 Timothy              Gates                     TGATES                    650.505.3876         11-JUL-06 SH_CLERK         2900                       122            50      3475.55556
            191 Randall              Perkins                   RPERKINS                  650.505.4876         19-DEC-07 SH_CLERK         2500                       122            50      3475.55556
    
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID DEPT_50_AVG_SAL
    ----------- -------------------- ------------------------- ------------------------- -------------------- --------- ---------- ---------- -------------- ---------- ------------- ---------------
            194 Samuel               McCain                    SMCCAIN                   650.501.3876         01-JUL-06 SH_CLERK         3200                       123            50      3475.55556
            195 Vance                Jones                     VJONES                    650.501.4876         17-MAR-07 SH_CLERK         2800                       123            50      3475.55556
            196 Alana                Walsh                     AWALSH                    650.507.9811         24-APR-06 SH_CLERK         3100                       124            50      3475.55556
            197 Kevin                Feeney                    KFEENEY                   650.507.9822         23-MAY-06 SH_CLERK         3000                       124            50      3475.55556
    
    37 rows selected.
    
    SQL> 
    

    SY.

  • Additional help for a SQL statement.

    I am needing help with a query related to one I got the help of yesterday. In this case, I have a table tasks are assigned to a task owner. Each task has an opening and a closing date - in some cases, tasks, closing date is null because the task is not yet complete.

    I am running Oracle Database 10 g Release 10.2.0.3.0 - 64 bit Production.

    It is an example of the data available in my table.
    CREATE TABLE     table_x
    (       owner_nm       VARCHAR2 (10)
    ,       task_nm        VARCHAR2 (10)
    ,       open_dt        DATE
    ,       closed_dt      DATE
    );
    
    INSERT INTO table_x (owner_nm, task_nm, open_dt, closed_dt) VALUES ('Curly', 'task b', DATE '2010-04-18', DATE '2010-10-14');
    INSERT INTO table_x (owner_nm, task_nm, open_dt, closed_dt) VALUES ('Moe',   'task a', DATE '2010-01-01', DATE '2010-12-01');
    INSERT INTO table_x (owner_nm, task_nm, open_dt, closed_dt) VALUES ('Moe',   'task c', DATE '2010-10-31', DATE '2011-01-01');
    INSERT INTO table_x (owner_nm, task_nm, open_dt, closed_dt) VALUES ('Moe',   'task e', DATE '2010-12-01', DATE '2011-02-21');
    INSERT INTO table_x (owner_nm, task_nm, open_dt, closed_dt) VALUES ('Larry', 'task d', DATE '2010-11-01', DATE NULL);
    I'm looking for the result set is a table that displays the total number of jobs open for each owner over time. If a task is not yet completed, the task should show as active all the way up to the date on which the query is executed. For example, if I run the query today, any task that has a null closed_dt value would be in the open_dt up to the current date.

    Here is an example of how I need to see my data in the above table.
    OWNER_NM    YEAR JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
    ---------- ----- --- --- --- --- --- --- --- --- --- --- --- ---
    Curly       2010   0   0   0   1   1   1   1   1   1   1   0   0
    Larry       2011   1   1   1   0   0   0   0   0   0   0   0   0
    Larry       2010   0   0   0   0   0   0   0   0   0   0   1   1
    Moe         2011   2   1   0   0   0   0   0   0   0   0   0   0
    Moe         2010   1   1   1   1   1   1   1   1   1   2   2   3
    Yesterday, I received the help of [Frank Kulash | http://forums.oracle.com/forums/profile.jspa?userID=627845], I was close to what I need. This is a variant of the query that Frank came with.
    WITH     got_month_cnt          AS
    (
         SELECT  owner_nm
         ,     TRUNC (open_dt, 'MONTH')     AS first_month
         ,     1 + MONTHS_BETWEEN ( TRUNC (closed_dt, 'MONTH')
                             , TRUNC (open_dt,   'MONTH')
                           )          AS month_cnt
         FROM    table_x
      WHERE owner_nm in ('Curly', 'Moe', 'Larry')
    )
    ,     cntr     AS
    (
         SELECT     LEVEL     AS n
         FROM     (
                   SELECT  MAX (month_cnt)     AS max_month_cnt
                   FROM     got_month_cnt
              )
         CONNECT BY     LEVEL     <= max_month_cnt
    )
    ,     all_months     AS
    (
         SELECT     m.owner_nm
         ,     ADD_MONTHS ( m.first_month
                      , c.n - 1
                      )          AS open_month
         FROM     got_month_cnt     m
         JOIN     cntr          c  ON     c.n     <= m.month_cnt
    )
    SELECT       owner_nm
    ,       EXTRACT (YEAR FROM open_month)                         AS year
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jan' THEN 1 ELSE 0 END)     AS jan
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Feb' THEN 1 ELSE 0 END)     AS feb
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Mar' THEN 1 ELSE 0 END)     AS mar
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Apr' THEN 1 ELSE 0 END)     AS apr
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'May' THEN 1 ELSE 0 END)     AS may
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jun' THEN 1 ELSE 0 END)     AS jun
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jul' THEN 1 ELSE 0 END)     AS jul
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Aug' THEN 1 ELSE 0 END)     AS aug
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Sep' THEN 1 ELSE 0 END)     AS sep
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Oct' THEN 1 ELSE 0 END)     AS oct
    ,       MAX (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Nov' THEN 1 ELSE 0 END)     AS nov
    ,       MAX (CASE WHEN TO_CHAR (OPEN_MONTH, 'Mon') = 'Dec' THEN 1 ELSE 0 END)     AS dec
    FROM       all_months
    GROUP BY  owner_nm
    ,       EXTRACT (YEAR FROM open_month)
    ORDER BY  owner_nm, year desc
    ,            year
    ;
    It is so close, but I need to make two changes to the addititional I've not been able to understand. (1) I can not understand how to summarize the months which overlap that occur in my data. (2) I have not been able to find a way consider the records containing nulls in the closed_dt field - in this case, I need them to count up to the current date.

    Thanks in advance for your time and your insight into this problem.

    David.

    Hi, David,.

    As John said, you will need to use NVL (or COALESCE) assimilate closed_dts NULL with SYSDATE.
    Aside from that, all you have to do is to use the SUM (rather than MAX) by rotating the data in the main query:

    WITH     got_month_cnt          AS
    (
         SELECT  owner_nm
         ,     TRUNC (open_dt, 'MONTH')     AS first_month
         ,     1 + MONTHS_BETWEEN ( TRUNC (NVL ( closed_dt          -- Changed (3 lines)
                                              , SYSDATE
                                  )    , 'MONTH')
                             , TRUNC (open_dt,   'MONTH')
                           )          AS month_cnt
         FROM    table_x
           WHERE owner_nm in ('Curly', 'Moe', 'Larry')
    )
    ,     cntr     AS
    (
         SELECT     LEVEL     AS n
         FROM     (
                   SELECT  MAX (month_cnt)     AS max_month_cnt
                   FROM     got_month_cnt
              )
         CONNECT BY     LEVEL     <= max_month_cnt
    )
    ,     all_months     AS
    (
         SELECT     m.owner_nm
         ,     ADD_MONTHS ( m.first_month
                      , c.n - 1
                      )          AS open_month
         FROM     got_month_cnt     m
         JOIN     cntr          c  ON     c.n     <= m.month_cnt
    )
    SELECT       owner_nm
    ,       EXTRACT (YEAR FROM open_month)                         AS year
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jan' THEN 1 ELSE 0 END)     AS jan     -- Changed (12 lines)
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Feb' THEN 1 ELSE 0 END)     AS feb
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Mar' THEN 1 ELSE 0 END)     AS mar
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Apr' THEN 1 ELSE 0 END)     AS apr
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'May' THEN 1 ELSE 0 END)     AS may
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jun' THEN 1 ELSE 0 END)     AS jun
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Jul' THEN 1 ELSE 0 END)     AS jul
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Aug' THEN 1 ELSE 0 END)     AS aug
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Sep' THEN 1 ELSE 0 END)     AS sep
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Oct' THEN 1 ELSE 0 END)     AS oct
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Nov' THEN 1 ELSE 0 END)     AS nov
    ,       SUM (CASE WHEN TO_CHAR (open_month, 'Mon') = 'Dec' THEN 1 ELSE 0 END)     AS dec
    FROM       all_months
    GROUP BY  owner_nm
    ,       EXTRACT (YEAR FROM open_month)
    ORDER BY  owner_nm
    ,            year     DESC
    --,          year          -- No point in repeating the same column
    ;
    

    In the sample data, you must meant:

    INSERT INTO table_x (owner_nm, task_nm, open_dt, closed_dt) VALUES ('Larry', 'task d', DATE '2010-11-01',  NULL);
    

    You can INSERT NULL in any column type: DATE, VARCHAR2, NUMBER or anything else. You don't have to distinguish the DATEs NULL NULL numbers.

    If we can mark questions as 'Correct', you will get 10 points for sure. Some people use this forum for years and have said several times how to ask a question, but yet have not learned. Keep up the good work!

    Published by: Frank Kulash, March 11, 2011 12:44

  • help automate an UPDATE with PL/SQL statement

    Hello, I'm on 10g R2, I am trying to learn PL/SQL, got a few books, watch YouTube videos and other things as best practices and etc. I wanted to automate this SQL:

    Basically every month I have to update a lot of old paintings against the current months Table.

    Old Table = your
    New Table = tt

    I thought maybe I can put anything in a list (like a table) and list all the old tables in there for your, I have 26 far and every month I add + 1.

    The tt table is only one, that's why I thought I could automate only inside a loop?
    UPDATE OLDER_TABLE_DATE ta
    
     SET (ta.GTP, ta.UPDATE_DT) = 
         (SELECT tt.GTP, SYSDATE
          FROM NEWEST_TABLE_UPDATED tt
          WHERE ta.customer_id = tt.customer_id
          AND ta.STAMP_DATE = tt.STAMP_DATE)
    
    WHERE EXISTS (SELECT 1
            FROM NEWEST_TABLE_UPDATED tt
            WHERE ta.customer_id = tt.customer_id
            AND ta.STAMP_DATE = tt.STAMP_DATE
            AND (NVL(ta.GTP, 'X') != NVL(tt.GTP, 'X')));
            
    COMMIT;
    What do you think guys? example or help would be appreciated. I can run this as an anonymous block for now, it is very good, thanks!

    Assumptions: -.
    -Your old/new all the tables are in the same schema.
    -Their names have the word "more ANCIENT".
    -You can run the procedure of the same pattern where all the tables of the old and the new spell.

    NOTE:-handle exceptions in the code accordingly, for example, when the update fails then handle exceptions.
    -As mentioned previously, this approach does not sound very well. Change in design to a single table (partition on month) stores all monthly data will be a good solution.

    CREATE OR REPLACE PROCEDURE UPDATE_TABLES_PROC
    AS
    cursor c1 is
    select table_name from user_tables
    where table_name like '%OLDER%';
    
    type t_current_table is table of c1%rowtype;
    v_current_table t_current_table;
    
    SQL_STMT VARCHAR2(3000):=0;
    
    BEGIN
    
    OPEN C1;
     LOOP
    
        FETCH C1 BULK COLLECT INTO  v_current_table  LIMIT 10; 
    
        IF v_current_table.count>0 then
    
        FOR i in v_current_table .first..v_current_table .last
        LOOP
    
        SQL_STMT:='UPDATE ' ||v_current_table(i).table_name|| ' ta
                         SET (ta.GTP, ta.UPDATE_DT) =
                                       (SELECT tt.GTP, SYSDATE
                                        FROM NEWEST_TABLE_UPDATED tt
                                        WHERE ta.customer_id = tt.customer_id
                                       AND ta.STAMP_DATE = tt.STAMP_DATE)
                          WHERE EXISTS (SELECT 1
                                       FROM NEWEST_TABLE_UPDATED tt
                                       WHERE ta.customer_id = tt.customer_id
                                       AND ta.STAMP_DATE = tt.STAMP_DATE
                                       AND (NVL(ta.GTP, ''X'') != NVL(tt.GTP, ''X'')))';
    
        EXECUTE IMMEDIATE SQL_STMT;
        EXIT WHEN c1%NOTFOUND;
    
        END LOOP;
        END IF;
    
    COMMIT;
    EXIT WHEN c1%NOTFOUND;
    END LOOP;
    CLOSE C1;
    END UPDATE_TABLES_PROC;
    

Maybe you are looking for