SQL Pivot help

Hello,
I have the following pivot that's working properly. It's adding up purchases into monthly time frame columns.  Is there anyway to add a second column called [redemptions]?  Ideally, I want it to sum up monthly purchases,  monthly
redemptions, then take the difference between the purchases and redemptions and call it new money.  So each month would have three columns labeled 20130531 Purchases, 20130531 Redemptions, 20130531 New Money., ...., etc....
SELECT * FROM [Assets].[dbo].[Monthly]
  pivot(sum(PURCHASES) for [DATE] IN
[20130531],
[20130628],
[20130731],
[20130830],
[20130930],
[20131031],
[20131129],
[20131231],
[20140131],
[20140228],
[20140331],
[20140430],
[20140530],
[20140630],
[20140731],
[20140829],
[20140930],
[20141031]
)) AS test
x

possible if you use classic crosstab method 
ie like
SELECT other columns...,
SUM(CASE WHEN [DATE] = '20130531' THEN PURCHASES ELSE 0 END) AS [20130531_PURCHASES],
SUM(CASE WHEN [DATE] = '20130531' THEN REDEMPTIONS ELSE 0 END) AS [20130531_REDEMPTIONS],
SUM(CASE WHEN [DATE] = '20130628' THEN PURCHASES ELSE 0 END) AS [20130628_PURCHASES],
SUM(CASE WHEN [DATE] = '20130628' THEN REDEMPTIONS ELSE 0 END) AS [20130628_REDEMPTIONS],
SUM(CASE WHEN [DATE] = '20130731' THEN PURCHASES ELSE 0 END) AS [20130731_PURCHASES],
SUM(CASE WHEN [DATE] = '20130731' THEN REDEMPTIONS ELSE 0 END) AS [20130731_REDEMPTIONS],
SUM(CASE WHEN [DATE] = '20141031' THEN PURCHASES ELSE 0 END) AS [20141031_PURCHASES],
SUM(CASE WHEN [DATE] = '20141031' THEN REDEMPTIONS ELSE 0 END) AS [20141031_REDEMPTIONS]
FROM [Assets].[dbo].[Monthly]
GROUP BY other columns...
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page

Similar Messages

  • 11G SQL pivot example?

    Hello,
    Can anyone help me write a SQL pivot statement using 11G to do the following?:
    Table columns
    =========
    Deliverable
    Phase (For simplicity we'll make the total possible Phase values equal 1 to 13)
    Delv_IN_Phase_Y_N Char(3) values 'Yes' or 'No'
    I want to make a matrix with these 3 columns in the above table (in reality a complex view) :
    - Deliverable is first column.
    - Next 13 column headers display 1 to 13 (the posiible values contained in the 'Phase' column).
    - The matrix values under the 'Phase' Column headers are the Yes/No values held in the Delv_in_Phase column.
    Deliverable Phase 1 Phase 2 Phase 3 Phase 4 ......... Phase 13
    =========================================================
    Product Market Plan Yes No No Yes No
    Bid Plan No Yes No ...........................................
    Contract Summary ................................................................................
    Quality Plan .................................................................................
    Thanks for any help in advance.
    Carol

    Just a simple example based on what I could grasp from your table description.
    I assume you can't have more than 1 value (either 'yes' or 'no' for a given deliverable in each phase).
    Connected to Oracle Database 11g Enterprise Edition Release 11.1.0.6.0
    Connected as fsitja
    SQL> with t as (
      2  select 'Product Market Plan' deliverable, 1 phase, 'NO' Delv_IN_Phase_Y_N from dual union all
      3  select 'Product Market Plan' deliverable, 2 phase, 'YES' Delv_IN_Phase_Y_N from dual union all
      4  select 'Product Market Plan' deliverable, 3 phase, 'YES' Delv_IN_Phase_Y_N from dual union all
      5  select 'Bid Plan', 1, 'YES' from dual union all
      6  select 'Bid Plan', 2, 'NO' from dual union all
      7  select 'Bid Plan', 3, 'NO' from dual union all
      8  select 'Contract Summary', 1, 'NO' from dual union all
      9  select 'Contract Summary', 2, 'NO' from dual union all
    10  select 'Contract Summary', 3, 'YES' from dual union all
    11  select 'Quality Plan', 1, 'YES' from dual union all
    12  select 'Quality Plan', 2, 'YES' from dual union all
    13  select 'Quality Plan', 3, 'NO' from dual)
    14  -- END OF SAMPLE DATA
    15  SELECT *
    16    FROM t
    17   PIVOT(MAX(delv_in_phase_y_n) FOR phase IN (1 AS phase_1, 2 AS phase_2, 3 AS phase_3))
    18  /
    DELIVERABLE         PHASE_1 PHASE_2 PHASE_3
    Contract Summary    NO      NO      YES
    Bid Plan            YES     NO      NO
    Product Market Plan NO      YES     YES
    Quality Plan        YES     YES     NO
    SQL> You can play around and expand the pivot by adding the whole 13 values inside the "FOR phase IN (val1 as column1, etc)" just thought I'd keep it simple.
    => [Documentation Reference here|http://download.oracle.com/docs/cd/E11882_01/server.112/e10592/statements_10002.htm#CHDCEJJE]
    Regards.

  • Dynamic SQL Pivoting(Converting Row to Columns)

    Hi All,
    I am using Oracle 9i (Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production)
    and also 10g version
    I am facing difficulties to find out the logic for
    converting the set of values in one of the columns into the column headings for the entire query.
    create TABLE my_tab ( deptno VARCHAR2(5), job VARCHAR2(50), sal NUMBER);
    insert into my_tab ( deptno,JOB, sal) values ( 10, 'ANALYST', 23000);
    insert into my_tab ( deptno,JOB, sal) values ( 10, 'SALESMAN', 1500);
    insert into my_tab ( deptno,JOB, sal) values ( 10, 'CLERK', 3550);
    insert into my_tab ( deptno,JOB, sal) values ( 20, 'SALESMAN', 700);
    insert into my_tab ( deptno,JOB, sal) values ( 20, 'ANALYST', 4200);
    insert into my_tab ( deptno,JOB, sal) values ( 30, 'SALESMAN', 5600);
    insert into my_tab ( deptno,JOB, sal) values ( 30, 'CLERK', 12000);
    insert into my_tab ( deptno,JOB, sal) values ( 30, 'ANALYST', 19000);
    COMMIT;
    SELECT * FROM my_tab
    DEPTNO ______ JOB ________ SAL
    10 ______ ANALYST ________ 23000
    10 ______ SALESMAN     ________     1500
    10     _______ CLERK     ________     3550
    20     _______     SALESMAN ________     700
    20     _______     ANALYST     ________ 4200
    30     _______     SALESMAN ________     5600
    30     _______     CLERK     _______          12000
    30     _______ ANALYST     _______     19000
    --And I wish to convert it into this structure:
    DEPTNO ________ ANALYST ________ SALESMAN _________ CLERK
    10      ________     23000 ________     1500     _________     3550
    20     ________ 4200 ________     700     _________     NULL
    30     ________ 19000 ________     5600     _________     12000
    It may be dynamic. i.e Later i inserted more two records into My_tab.
    insert into my_tab ( deptno,JOB, sal) values ( 20, 'CLERK', 3400);
    insert into my_tab ( deptno,JOB, sal) values ( 30, 'MANAGER', 48000);
    So it should be dynamic.
    output is like this.
    DEPTNO ________ ANALYST ______ SALESMAN ______ CLERK ______ MANAMGER
    10           ________ 23000     ______ 1500     ______ 3550     ______     NULL
    20          ________ 4200     ______ 700     ______ 3400     ______     NULL
    30          ________ 19000     ______ 5600     ______ 12000     ______     48000
    Please help me regarding this.
    With warm regards,
    Prasanta

    Hi, Prasanta,
    Displaying one column from many rows as many columns on one row is called Pivoting . The following thread shows the basics of how to pivot:
    Help for a query to add columns
    That example uses the aggregate COUNT function; you'll want SUM (or possibly MIN or MAX) instead.
    Getting a dynamic number of columns requires Dynamic SQL . As a simpler alternative to pivoting and dynamic SQL, you might consider String Aggregation , where you concatenate a column from many rows into one big string, to be displayed on one row.
    See the following thread for more about string aggregation and other options on pivoting into a variable number of columns:
    Re: Report count and sum from many rows into many columns

  • Can we use multiple "pivot_for_clauses" in 11g SQL PIVOT

    Can we use multiple "pivot_for_clauses" in 11g SQL PIVOT. Below SQL is an example of what I am trying to do - In this case instead of using JOIN, can I have three pivot_for_clauses in the same sql?
    SQL:
    MERGE INTO Test_1 dest
    USING (SELECT P1.company_id,trunc(sysdate) as load_date,num_logins,......
    FROM (SELECT company_id,action_type_id
    FROM Testauditinfo_1 where trunc(audit_date_time)=trunc(sysdate)-1) a
    PIVOT (count(action_type_id) FOR (action_type_id) IN ((1) as num_logins,(2) as num_logouts,(61) as
    num_logins_from_mobile_device,(16) as num_pref_changed,....)) P1
    JOIN
    (SELECT company_id,action_type_id,tx_type_id
    FROM Testauditinfo_1 where trunc(audit_date_time)=trunc(sysdate)-1) a
    PIVOT (count(action_type_id) FOR (action_type_id,tx_type_id) IN ((3,4) AS add_invoice, (4,4) AS
    edit_invoice,(3,3) as num_checks,(3,47) as num_paychecks,(3,7) as num_recvd_payments,(3,9) as num_bills,
    (3,35) as num_estimates,(3,46) as num_purchase_orders)) P2
    on P1.company_id=P2.company_id
    JOIN
    (SELECT company_id,action_type_id,list_type_id
    FROM Testauditinfo_1 where trunc(audit_date_time)=trunc(sysdate)-1) a
    PIVOT (count(action_type_id) FOR (action_type_id,list_type_id) IN ((3,2) AS num_items,(3,1) as
    num_accounts,(3,4) as num_employees,(3,6) as num_customers,(3,14) as num_memorized_reports)) P3
    on P2.company_id=P3.company_id
    left outer JOIN
    (SELECT company_id,create_date,count(*) as num_logos
    FROM qbo.companylogos_1 group by company_id,create_date having trunc(create_date)=trunc(sysdate)-1) P4
    on P3.company_id=P4.company_id
    ORDER BY P1.company_id) source
    ON ((dest.company_id = source.company_id) and (dest.load_date = source.load_date))WHEN MATCHED THEN
    UPDATE SET dest.num_items = source.num_items where 1=2
    WHEN NOT MATCHED THEN
    INSERT (dest.company_id,.....) values (source.company_id,.....);

    Maybe
    MERGE INTO Test_1 dest
    USING (SELECT P1.company_id,trunc(sysdate) as load_date,num_logins,......
             FROM (select *
                     from (SELECT company_id,action_type_id
                             FROM Testauditinfo_1
                            where trunc(audit_date_time) = trunc(sysdate)-1
                          ) a
                          PIVOT (count(action_type_id)
                            FOR (action_type_id) IN ((1) as num_logins,
                                                     (2) as num_logouts,(61) as num_logins_from_mobile_device,
                                                     (16) as num_pref_changed,....
                  ) P1
                  JOIN
                  (select *
                     from (SELECT company_id,action_type_id,tx_type_id
                             FROM Testauditinfo_1
                            where trunc(audit_date_time) = trunc(sysdate)-1
                          ) a
                          PIVOT (count(action_type_id)
                            FOR (action_type_id,tx_type_id) IN ((3,4) AS add_invoice,
                                                                (4,4) AS edit_invoice,
                                                                (3,3) as num_checks,
                                                                (3,47) as num_paychecks,
                                                                (3,7) as num_recvd_payments,
                                                                (3,9) as num_bills,
                                                                (3,35) as num_estimates,(3,46) as num_purchase_orders
                  ) P2
               on P1.company_id = P2.company_id
                  JOIN
                  (select *
                     from (SELECT company_id,action_type_id,list_type_id
                             FROM Testauditinfo_1
                            where trunc(audit_date_time) = trunc(sysdate)-1
                          ) a
                          PIVOT (count(action_type_id)
                            FOR (action_type_id,list_type_id) IN ((3,2) AS num_items,
                                                                  (3,1) as num_accounts,
                                                                  (3,4) as num_employees,
                                                                  (3,6) as num_customers,
                                                                  (3,14) as num_memorized_reports
                  ) P3
               on P2.company_id = P3.company_id
                  left outer JOIN
                  (SELECT company_id,create_date,count(*) as num_logos
                     FROM qbo.companylogos_1
                    group by company_id,create_date
                    having trunc(create_date) = trunc(sysdate)-1
                  ) P4
               on P3.company_id = P4.company_id
            ORDER BY P1.company_id
          ) source
       ON ((dest.company_id = source.company_id) and (dest.load_date = source.load_date))
    WHEN MATCHED
    THEN UPDATE SET dest.num_items = source.num_items where 1 = 2
    WHEN NOT MATCHED
    THEN INSERT (dest.company_id,.....)
          values (source.company_id,.....)Did you try it ?
    Regards
    Etbin

  • SQL*Plus Help

    Hi! Does anyone know where i can download SQL*Plus Help? I need to get info on select syntax, sql built-in functions, etc..
    Thanks!

    hi
    you can proceed like this :
    go to the OTN
    the click on products.
    null

  • How to install SQL*Plus help facilities and demos.

    Hi, everyone
    It appears error message say "failure to login" during SQL*Plus
    part of the Oracle8 full installation. I knew that system want
    to install SQL*Plus help and demos through logining one of
    dba account(maybe system user account). However, due to
    password's reason, can not log in SQL*Plus, so installer can't
    execute named pupbld.sql script, result in SQL*Plus help and
    demos can not be installed.
    Now, I am intend to install these stuff lonely.
    Could anyone help me? thank a lot.
    William
    null

    Hi,
    The pupbld.sql isn't the correct script to create the help
    facility, it just creates product and user profile tables.
    The help script is at $ORACLE_HOME/sqlplus/admin/help (run as
    system)
    cd $ORACLE_HOME/sqlplus/admin/help
    sqlplus system/<password> @helptbl
    sqlldr system/<password> control=plushelp.ctl
    sqlldr system/<password> control=plshelp.ctl
    sqlldr system/<password> control=sqlhelp.ctl
    sqlplus system/<password> @helpindx
    I think it is necessary to run the pupbld.sql script, without
    this script everyone who logins in oracle with sqlplus will see
    an error message, but... Run the script again:
    $ORACLE_HOME/sqlplus/admin/pupbld.sql
    Best regards,
    Ari
    William (guest) wrote:
    : Hi, everyone
    : It appears error message say "failure to login" during SQL*Plus
    : part of the Oracle8 full installation. I knew that system want
    : to install SQL*Plus help and demos through logining one of
    : dba account(maybe system user account). However, due to
    : password's reason, can not log in SQL*Plus, so installer can't
    : execute named pupbld.sql script, result in SQL*Plus help and
    : demos can not be installed.
    : Now, I am intend to install these stuff lonely.
    : Could anyone help me? thank a lot.
    : William
    null

  • Will Oracle pl/sql certification help me get  IT job

    Hello guys,
    I have completed my B.tech in Computer Science, I am confused a bit , Can i get a job after getting certified in Oracle Associate Pl/sql developer

    1005323 wrote:
    Hello guys,
    I have completed my B.tech in Computer Science, I am confused a bit , Can i get a job after getting certified in Oracle Associate Pl/sql developerYou may get a job after achieving Pl/sql developer OCA
    You may get a job after without achieving Pl/sql developer OCA
    You may fail to get a job after achieving Pl/sql developer OCA
    You may fail to get a job after without achieving Pl/sql developer OCA
    There are several factors involved in getting a job. And there are several ways a job may be obtained. But usually there are there stages:
    - Stage Zero: A company but has a job to offer.
    - And you need to be aware of it. - A friend may tell you, or an agency may tell you. And it must suit you for location and remuneration etc.
    - Stage one: An interview is obtained with the company.
    - Stage two: The job is offered to you rather than anyone else and you find it acceptable.
    So ... to your question:
    "Can i get a job after getting certified in Oracle Associate Pl/sql developer?"
    Well .... there is only three possible answers ... yes, no, and maybe; and maybe is probably the only correct answer, and most people will have worked this out, which means the question may have not been the best question to have asked.
    (( That said I now read the title of the thread and it says: Re: Will Oracle pl/sql certification help me get IT job)
    I have been known on occasion to have been given a question by a boss.
    And I have answered him:
    "You have given me the wrong question
    The question you should have answer me is this.
    And the answer I will give you is this."
    And the boss goes away happy
    So you you a better question would have been:
    How much will an OCA PL/SQL certification increase my chances of getting a job?
    Mind you even that question won't help you get a much better answer.
    For a proportion of jobs where PL/SQL is relevant that will help (for those where it is not it might be occasionally be a problem), for people with identical CV's it sometimes might help get to interview stage. But there are other factors as well. For instance if I was thinking of giving you a job on the basis of your post I might for example:
    - Not be impressed with an "Hello Guys" greeting ( though this is a forum so that isn't relevant here).
    - Not be impressed with you being confused.
    - etc.
    You probably need to get a good appreciation of the job market in your locality; and the numbers of applicants for each job. Which jobs you can apply for, what is your skillset and knowing youself as well.
    Sometimes an ITIL certification may be a better differentiator for some positions in business. But it will depend on the job you can think you can get.

  • (SQL*PLUS HELP) RUNNING PUPBLD OR HELPINS ASKS FOR SYSTEM_PASS

    제품 : ORACLE SERVER
    작성날짜 : 2002-04-22
    (SQL*PLUS HELP) RUNNING PUPBLD OR HELPINS ASKS FOR SYSTEM_PASS
    ==============================================================
    PURPOSE
    이 내용은 SQL*Plus 상에서 SQL*Plus command의 help를 보기 위한 방법이다.
    Problem Description
    SQL*Plus command의 help를 보기 위해서 helpins를 수행하면
    SYSTEM_PASS is not set이라는 에러 메시지가 발생하는 경우가 있다.
    이 자료는 pupbld 또는 helpins를 수행하기 전에 SYSTEM_PASS 환경변수를
    셋팅하는 방법에 대한 자료이다.
    아래와 같은 에러가 발생하는 경우 조치 방법에 대해 알아본다.
    SYSTEM_PASS not set.
    Set and export SYSTEM_PASS, then restart help (for helpins or
    profile for pupbld) installation.
    Workaround
    none
    Solution Description
    이 스크립트는 system user로 database에 connect되어 수행되어야 한다.
    helpins를 수행하기 위해서는 SYSTEM_PASS 환경변수가 셋팅되어 있어야 한다.
    NOTE
    For security reasons, do not set this variable in your shell
    startup scripts. (i.e. .login or .profile.).
    Set this environment variable at the prompt.
    1. Prompt에서 환경변수를 셋팅하기
    For C shell:
    % setenv SYSTEM_PASS system/<password>
    For Korn or Bourne shells:
    $ SYSTEM_PASS=system/<password> ;export SYSTEM_PASS
    2. Now run "$ORACLE_HOME/bin/pupbld" or "$ORACLE_HOME/bin/helpins".
    % cd $ORACLE_HOME/bin
    % pupbld
    or
    % helpins
    주의사항
    $ORACLE_HOME/bin/pupbld 스크립트와 $ORACLE_HOME/bin/helpins 스크
    립트를 수행하기 위해서는 반드시 SYSTEM_PASS 환경변수를 필요로 한다.
    Reference Document
    <Note:1037075.6>

    check it please whether it is a database version or just you are installing a client. Install Enterprize database on 2k system. I you are running a client software then you are to deinstall it.

  • Download Oracle SQL*Plus help related like word help

    Hello all
    I just wanna ask if where i can download Oracle SQL*Plus help related like word help.?
    ty

    <p>You can access SQL*Plus help from the command line in a SQL*Plus session by typing 'help index'. If you want more information than that, take a look at the SQL*Plus Quick Reference located <b>here</b> or the SQL*Plus User's Guide and Reference located <b>here</b>. These docs are all for Oracle 10g. Other version documentation can be found <b>here</b>.</p>
    Tom

  • SQL Server2008 help needed

    Having trouble with SQLServer 2008 (not MySQL) and my database connection in Dreamweaver CS6.  My document type is set as .asp using VBScript.  I can list the table information  but cannot use the insert wizard to add new records.  I don't get any errors after creating the insert form, but no records get inserted.  I'm not a VBScript expert, but do I have to manually write some code to insert records?  How do I attach it to a button?

    Thanks for the quick reply.  I won't be back in the office for a few days, but I'll try to post it when I get back in.  It's pretty much the code generated from the Dreamweaver Insert Record wizard.  I see where the submit button is created and the value is set but the action on the form is set to MM_insert, so I don't see where the submit code is actually called.
    Date: Wed, 3 Oct 2012 12:06:14 -0600
    From: [email protected]
    To: [email protected]
    Subject: SQL Server2008 help needed
        Re: SQL Server2008 help needed
        created by bregent in Dreamweaver General - View the full discussion
    This post should be moved to the app dev forum.  Please post the code from your form and the insert script pages.
         Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at http://forums.adobe.com/message/4746757#4746757
         Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page: http://forums.adobe.com/message/4746757#4746757
         To unsubscribe from this thread, please visit the message page at http://forums.adobe.com/message/4746757#4746757. In the Actions box on the right, click the Stop Email Notifications link.
         Start a new discussion in Dreamweaver General by email or at Adobe Community
      For more information about maintaining your forum email notifications please go to http://forums.adobe.com/message/2936746#2936746.

  • SQL pivot query help

    HUM ADG DYS (NIA, SIM, TRC, TRX) SMALL BRANDS (LUP, KAL,CRN,LPP,SYN)
    MON TUE WED THURS FRI MON TUE WED THURS FRI MON TUE WED THURS FRI MON TUE WED THURS FRI
    VENDOR
    INT
    QUAN
    STER
    LASH
    OSP
    HIB
    PROD
    I’d like to put together a query to populate the tables above,like count of recods for each vendor for each brand with the criteria for selecting within one week.
    Here vendor_cd(INT,QUAN,STER,...etc),brand_cd(HUM,ADG,NIA,SIM,..eyc).we are extracting the details from file detail table whose column are like FILE_ID,FILE_RECEIPT_TS,REC_INSERT_TS,VENDOR_CD,BRAND_CD,RECORD_COUNT.
    Edited by: ASHWINI89 on Mar 21, 2013 8:33 PM

    Welcome to the forum!!
    Please consider the following when you post a question. This would help us help you better
    1. New features keep coming in every oracle version so please provide Your Oracle DB Version to get the best possible answer.
    You can use the following query and do a copy past of the output.
    select * from v$version 2. This forum has a very good Search Feature. Please use that before posting your question. Because for most of the questions
    that are asked the answer is already there.
    3. We dont know your DB structure or How your Data is. So you need to let us know. The best way would be to give some sample data like this.
    I have the following table called sales
    with sales
    as
          select 1 sales_id, 1 prod_id, 1001 inv_num, 120 qty from dual
          union all
          select 2 sales_id, 1 prod_id, 1002 inv_num, 25 qty from dual
    select *
      from sales 4. Rather than telling what you want in words its more easier when you give your expected output.
    For example in the above sales table, I want to know the total quantity and number of invoice for each product.
    The output should look like this
    Prod_id   sum_qty   count_inv
    1         145       2 5. When ever you get an error message post the entire error message. With the Error Number, The message and the Line number.
    6. Next thing is a very important thing to remember. Please post only well formatted code. Unformatted code is very hard to read.
    Your code format gets lost when you post it in the Oracle Forum. So in order to preserve it you need to
    use the {noformat}{noformat} tags.
    The usage of the tag is like this.
    <place your code here>\
    7. If you are posting a *Performance Related Question*. Please read
       {thread:id=501834} and {thread:id=863295}.
       Following those guide will be very helpful.
    8. Please keep in mind that this is a public forum. Here No question is URGENT.
       So use of words like *URGENT* or *ASAP* (As Soon As Possible) are considered to be rude.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Sql aggregate help using month

    Hello guys.. I need your help in the below query..
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    create table test_12 ( co_cd varchar2 (10),
    dt date,
    sale number(10));
    insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','01-09-2000','250.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','04-09-2000','350.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','01-12-2000','450.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('CO','01-09-2000','950.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('CO','05-09-2000','250.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('TI','07-09-2000','750.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','09-09-2000','150.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('AB','02-09-2000','850.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('AB','01-09-2000','250.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('TI','04-09-2000','850.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','06-09-2000','550.00');
    insert into test_12 (CO_CD,DT,SALE) VALUES ('CO','02-09-2000','250.00');
    COMMIT;
    the target data should be aggregated sales for last 15 months of data for each company code
    CO_CD JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
    CO 950 250 0 0 0
    TI 0 0 850
    thanks

    Hi,
    Thanks for posting the CREATE TABLE and INSERT statements. That really helps to understand the problem, and to make sure that the answers actually do work.
    If you post code that doesn't work, then it's not so helpful. None of your INSERT statements work for me. They may work for you, depeneing on you NLS settings, but you sshouldn't use strings, such as '01-09-2000' in place of a DATE. Use TO_DATE to convert string like that into DATEs.
    Also, don't INSERT strings like '250.00' in place of a NUMBER. Lose the quotes. so it would be better if you posted statements like this:
    insert into test_12 (CO_CD,DT,SALE) VALUES ('LC', TO_DATE ('01-09-2011',  'MM-DD-YYYY'), 250.00);How do you get the results you posted for that sample data? It looks like none of the dts are in the last 120 months, let alone the last 15 months.
    Why do you want output rows for co_cds 'CO' and 'TI', but not for 'AB' and 'LC'?
    Please format your output, so people can tell which number is in which column. Whenever you post formatted text (such as query results) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    If the "last 15 months" means the 15 consecutive months ending with the current calendar month, then you can do something like this:WITH     got_month_num     AS
         SELECT     co_cd
         ,     MONTHS_BETWEEN ( TRUNC (SYSDATE, 'MONTH')
                   , TRUNC (dt,      'MONTH')
                   ) AS month_num
         ,     sale
         FROM     test_12
         WHERE     dt     >= ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), -14)     -- For efficiency
         AND     dt     < ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), 1)
    SELECT     *
    FROM     got_month_num
    PIVOT     (     SUM (sale)
         FOR     month_num IN ( 0     AS this_month
                   , 1     AS "1 Month Ago"
                   , 2     AS "2 Months Ago"
                   , 14     AS "14 Months Ago"
    ORDER BY co_cd
    If "the last 15 months" means something else, then just change the definition of month_num in the sub-query.
    If you want less generic column names (e.g. 'APR_2011') that change automatically, depending on when the query is run and/or what data is found in the table, then you have to use dynamic SQL.  This isn't very hard in SQL*Plus: you can do a separate preliminary query to set sione substritution varaibles, and then use those variables as the column alaises in the PIVOT clause.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Dynamic number of PL/SQL tables help!!!

    Hi,
    I have a PL/SQL code in which I am using PL/SQL table of tables.
    The number of such tables created in the code can be dynamic.
    At the end of the procedure I want to insert the records from those PL/SQL tables into a database table.
    Something like this.
    insert into DBL.RA_CONTROL_REPORT (time_slot1,time_slot2,time_slot3,time_slot4,time_slot5,time_slot6,time_slot7,
    time_slot8,time_slot9,time_slot10,time_slot11,time_slot12,time_slot13,time_slot14,time_slot15,time_slot16,
    time_slot17,time_slot18,time_slot19,time_slot20,time_slot21,time_slot22,time_slot23,time_slot24,time_slot25,
    time_slot26,time_slot27,time_slot28,time_slot29,time_slot30,time_slot31,time_slot32,time_slot33,time_slot34,
    time_slot35,time_slot36,time_slot37,time_slot38,time_slot39,time_slot40,time_slot41,time_slot42,time_slot43
    ,time_slot44,time_slot45,time_slot46,time_slot47,time_slot48)
    values ( Outer_table(1)(i),Outer_table(2)(i),Outer_table(3)(i),Outer_table(4)(i),Outer_table(5)(i)
    ,Outer_table(6)(i),Outer_table(7)(i),Outer_table(8)(i),Outer_table(9)(i),Outer_table(10)(i),Outer_table(11)(i)
    ,Outer_table(12)(i),Outer_table(13)(i),Outer_table(14)(i),Outer_table(15)(i),Outer_table(16)(i),Outer_table(17)(i)
    ,Outer_table(18)(i),Outer_table(19)(i),Outer_table(20)(i),Outer_table(21)(i),Outer_table(22)(i),Outer_table(23)(i)
    ,Outer_table(24)(i),Outer_table(25)(i),Outer_table(26)(i),Outer_table(27)(i),Outer_table(28)(i),Outer_table(29)(i)
    ,Outer_table(30)(i),Outer_table(31)(i),Outer_table(32)(i),Outer_table(33)(i),Outer_table(34)(i),Outer_table(35)(i)
    ,Outer_table(36)(i),Outer_table(37)(i),Outer_table(38)(i),Outer_table(39)(i),Outer_table(40)(i),Outer_table(41)(i)
    ,Outer_table(42)(i),Outer_table(43)(i),Outer_table(44)(i),Outer_table(45)(i),Outer_table(46)(i),Outer_table(47)(i)
    ,Outer_table(48)(i));
    Here, DBL.RA_CONTROL_REPORT is my database table.
    And each Outer_table()() is my PL/SQL table.
    I need to make this query dynamic by inserting only from those many number of PL/SQL tales which are created.
    Assume that I know the number of PL/SQL tables created.
    But when I try to do so, and apply execute immediate to that query. It gives me an error as unimplemented feature.
    Sample code where I have tried doing so is as follows:
    Query3:='insert into DBL.RA_CONTROL_REPORT (';
    for i in 1..max_cnt loop
    for idx in 1..Interval_Count loop
    col_name :=col_name||'time_slot'||idx||',';
    table_name :=table_name||'Outer_table('||idx||')('||i||'),';
    end loop;
    col_name:=rtrim(col_name,',');
    table_name:=rtrim(table_name,',');
    Query3:=Query3||col_name||') values('||table_name||')';
    dbms_output.put_line(query3);
    execute immediate query3;
    commit;
    end loop;
    Where max_cnt -> No of PL/SQL tables created.
    Please help.

    Now using the above approach to determine the bucket for a row, this result can be (outer) joined to the 48 buckets for the day and one can determine whether there are values for that bucket or not.
    For example:
    SQL> with MV as(
      2          select
      3                  trunc(sysdate)+(dbms_random.value(1,24)/24) as TIME,
      4                  trunc(dbms_random.value(1,100)) as B
      5          from    dual
      6          connect by level <= 1000
      7  ),
      8  DATA_BUCKETS as(
      9          select
    10                  time,
    11                  --// determine the decimal hour
    12                  (to_number(to_char(time,'hh24'))*60)
    13                  +to_number(to_char(time,'mi'))          as MINUTES,
    14                  --// use the decimal minute to determine
    15                  --// which half-hour bucket it goes into
    16                  trunc(  ((to_number(to_char(time,'hh24'))*60)+
    17                          +to_number(to_char(time,'mi')))
    18                          /30
    19                  )+1                                     as BUCKET,
    20                  b
    21          from    mv
    22  ),
    23  ACTUAL_BUCKETS as(
    24          select
    25                  level as BUCKET
    26          from    dual
    27          connect by level <= 48
    28  )
    29  select
    30          actual_buckets.bucket,
    31          sum(b),
    32          case    --// is there data in the data bucket?
    33                  when sum(data_buckets.b) is null then 'No'
    34          else
    35                  'Yes'
    36          end             as BUCKET_HAS_DATA
    37  from       actual_buckets,
    38          data_buckets
    39  where      actual_buckets.bucket = data_buckets.bucket (+)
    40  group by
    41          actual_buckets.bucket
    42  order by 1
    43  /
        BUCKET     SUM(B) BUCKET_HAS_DATA
             1            No
             2            No
             3       1321 Yes
             4       1582 Yes
             5       1409 Yes
             6        786 Yes
             7       1082 Yes
             8       1323 Yes
             9        998 Yes
            10       1462 Yes
            11        850 Yes
            12        947 Yes
            13       1033 Yes
            14       1224 Yes
            15        655 Yes
            16        810 Yes
            17       1319 Yes
            18        702 Yes
            19        994 Yes
            20        671 Yes
            21       1136 Yes
            22       1199 Yes
            23       1034 Yes
            24       1184 Yes
            25       1470 Yes
            26        890 Yes
            27       1549 Yes
            28        740 Yes
            29       1229 Yes
            30        833 Yes
            31       1159 Yes
            32       1613 Yes
            33       1234 Yes
            34        770 Yes
            35       1196 Yes
            36       1324 Yes
            37       1263 Yes
            38       1155 Yes
            39        785 Yes
            40       1130 Yes
            41       1286 Yes
            42       1056 Yes
            43       1462 Yes
            44       1032 Yes
            45        831 Yes
            46        888 Yes
            47        806 Yes
            48        995 Yes
    48 rows selected.
    SQL>I leave the pivot of this into a single row with 48 columns for you to research and figure out. I'm also pretty sure that other forum members can provide a lot more elegant examples than what I've done here.
    The point is that SQL is a very powerful and very capable data processing language. And if you want to build Oracle solutions that are robust and performant and scalable, then you need to Mamimise Maximise SQL and Minimise PL/SQL*.
    In other words - do not use PL/SQL when SQL can do the job better and faster.
    Edited by: Billy Verreynne on Sep 16, 2011 9:40 AM

  • SQL Pivot Query

    Hi Experts
    I recently purchased a copy of Gordon's book to help me create a pivot query based on the examples at the end which I hope to show me a set of data based on my Sales Order tables.   Unfortunately I have found it a little too complex.
    In my ORDR table I have 10 UDFs which relate to various statuses and dates in the sales order process. 
    What I would like is to see a pivot table query of the sum quanties of items at the different stages (as rows) against the dates in weeks.
    In the rows would be the status UDF fields:
    U_DES_STAGE
    U_PRN_STAGE
    U_PRS_STAGE
    U_SEW_STAGE
    U_EMB_STAGE
    for each UDF there is an associated date UDF
    U_DES_STAGE_DATE
    U_PRN_STAGE_DATE
    U_PRS_STAGE_DATE
    U_SEW_STAGE_DATE
    U_EMB_STAGE_DATE
    The columns I require in the pivot table would be the UDF stage dates which are always input for the week ending Friday.
    The data in the pivot should be the sum of the quantities in the sales orders rows RDR1.
    Stage
    W/E 14/3/2014
    W/E 21/3/2014
    W/E 28/3/2014
    W/E 4/4/2014
    W/E 11/4/2014
    W/E 18/4/2014
    DES
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    PRN
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    PRS
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    SEW
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    EMB
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    Sum of Qty
    The problem is that I am not sure as to how to add the WHERE clause to limit the results to only the 5 items (DES% or PRN% or PRS% or SEW% or EMB%)
    I would be very grateful for any assistance.
    Regards
    Geoff

    Hi Gordon - you're very welcome.   The content of the book is very helpful to an SQL novice!
    Essentially the 10 UDF are for recording each stage of the processes involved in the sales order.    there are 5 processes so each process has 2 fields - one records the initals of the staff member who is responsible and the other records the date the process is scheduled for.
    We want to be able to produce a schedule to show us how many garments are scheduled on a sales order in a particular week effectively turning this table into the one below it:
    Document Number
    Quantity
    Design - Scheduled Date
    Dye Print Scheduled Date
    Dye Press Scheduled Date
    Dye Sewing Scheduled Date
    Embroidery - Scheduled Date
    Print – Scheduled Date
    298835
    315
    12.07.10
    06.09.10
    300058
    144
    22.07.10
    06.09.10
    300921
    29
    01.10.10
    302330
    15
    30.09.10
    30.09.10
    302820
    460
    05.10.10
    302833
    55
    20.09.10
    22.09.10
    303476
    86
    06.10.10
    06.10.10
    303948
    13
    11.08.10
    11.08.10
    303982
    106
    26.10.10
    27.10.10
    304012
    99
    25.11.10
    25.11.10
    304186
    6
    27.08.10
    27.08.10
    304331
    10
    07.09.10
    07.09.10
    304382
    16
    29.09.10
    29.09.10
    304399
    15
    19.08.10
    304556
    85
    01.10.10
    22.10.10
    304557
    11
    29.09.10
    29.09.10
    304563
    8
    29.09.10
    29.09.10
    304567
    7
    29.09.10
    304570
    19
    01.10.10
    22.10.10
    304571
    113
    01.10.10
    22.10.10
    304576
    11
    29.09.10
    29.09.10
    304603
    72
    22.09.10
    23.09.10
    304604
    86
    22.09.10
    23.09.10
    304606
    107
    22.09.10
    23.09.10
    304608
    107
    22.09.10
    23.09.10
    304613
    107
    22.09.10
    23.09.10
    304693
    12
    29.09.10
    29.09.10
    304710
    5
    29.09.10
    304760
    6
    29.09.10
    29.09.10
    304765
    4
    29.09.10
    304899
    42
    15.09.10
    304963
    100
    22.09.10
    24.09.10
    304974
    719
    27.09.10
    29.09.10
    304975
    401
    28.09.10
    29.09.10

  • Pivot help on an heirarchy query

    I've looked through the FAQs but I'm just not seeing it.
    I have the following:
    A query returning:
    o_id   oname            typ  prnt
    118    Pension Admin    PRC    91
    91     Retirement       LOB   218
    218    Benefits         SEG    81
    119    Plan Mgmt        PRC    91
    91     Retirement       LOB   218
    218    Benefits         SEG    81
    142    RCS Software     PRC    93
    93     Risk Software    LOB   221
    221    Risk Services    SEG    81I want the following:
    ID  PRC              LOB               SEG
    118 Pension Admin    Retirement        Benefits
    119 Plan Mgmt        Retirement        Benefits
    142 RCS Software     Risk Software     Risk ServicesVersion:
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    PL/SQL Release 11.2.0.1.0 - Production
    CORE 11.2.0.1.0 Production
    TNS for Linux: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production
    Sample data:
    create table t1( o_id  number(3)
                   , oname varchar2(20)
                   , typ  varchar2(3)
                   , prnt number(3)
    insert into t1 values(118,   'Pension Admin',  'PRC',  91);
    insert into t1 values(91,    'Retirement',     'LOB', 218);
    insert into t1 values(218,   'Benefits',       'SEG',  81);
    insert into t1 values(119,   'Plan Mgmt',      'PRC',  91);
    insert into t1 values(142,   'RCS Software',   'PRC',  93);
    insert into t1 values(93,    'Risk Software',  'LOB', 221);
    insert into t1 values(221,   'Risk Services',  'SEG',  81);I can't get past:
    select level lvl, org.*
      from t1 org
      start with typ = 'PRC'
      connect by  o_id =  prior prnt;I've tried this, but of course it returns only one row:
    select *
      from (
             select lvl, oname
               from ( 
                      select level lvl, t1.*
                        from t1
                       start with typ = 'PRC'
                     connect by  o_id =  prior prnt
    pivot ( min(oname)  for lvl in (1  prc, 2 lob, 3 seg) )What am I missing, any help would be appreciated.

    Hi,
    Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful!
    Use CONNECT_BY_ROOT to remember the starting point that led to each row of output, which is what identifies which row of output each row of the CONNECT BY results corresponds to.
    Sorry, I'm not at an Oracle 11 system now. This works in Oracle 10 (and up):
    WITH     connect_by_results     AS
         SELECT     LEVEL               AS lvl
         ,      oname
           ,     CONNECT_BY_ROOT     o_id     AS starting_o_id
         FROM     t1
           START WITH     typ      = 'PRC'
         CONNECT BY     o_id      =  PRIOR prnt
    SELECT       starting_o_id
    ,       MIN (CASE WHEN lvl = 1 THEN oname END)     AS prc
    ,       MIN (CASE WHEN lvl = 2 THEN oname END)     AS lob
    ,       MIN (CASE WHEN lvl = 3 THEN oname END)     AS seg
    FROM       connect_by_results
    GROUP BY  starting_o_id
    ORDER BY  starting_o_id
    ;You can adapt the main query to use SELECT ... PIVOT.
    Do you really need separate columns for the different levels? If not, you could do something like this:
    SELECT     CONNECT_BY_ROOT     o_id     AS starting_o_id
    ,      REPLACE ( SYS_CONNECT_BY_PATH ( RPAD (oname, 15)
                              , '`'
              , '`'
              )     AS prc_lob_seg
    FROM     t1
    WHERE     CONNECT_BY_ISLEAF     = 1
    START WITH     typ      = 'PRC'
    CONNECT BY     o_id      =  PRIOR prnt
    ORDER BY     starting_o_id
    ;Ouptut:
    STARTING_O_ID PRC_LOB_SEG
              118 Pension Admin  Retirement     Benefits
              119 Plan Mgmt      Retirement     Benefits
              142 RCS Software   Risk Software  Risk ServicesNot only is this simpler, it works for any number of levels.
    Edited by: Frank Kulash on Jan 16, 2012 4:25 PM
    Added SYS_CONNECT_BY_PATH alternative.

Maybe you are looking for

  • How much does Premiere Pro and After Effects rely on the hard drive it's installed on?

    This may be a really dumb question, but how much does Premiere Pro and After Effects rely on the hard drive it's installed on if all your video files, assets, disk cache, etc are on different drives than the one the program itself is installed on? Th

  • Best aproach to zoom in on a clip

    What would be the best apporach to zoom on a certain area on a clip? Is there a plugin to do this automaticaly?

  • PFAL missing data idoc

    Hi Data is being transferred from HR system to SRM system using PFAL but idocs in SRM system are getting failed with error ' missing data' detailed desc shows that infotype 1001 subtype A209 data is missing and Business partner cannot be created. How

  • RACCT not found / Message no. K9806

    Budget Planning in T-Code FMPLCPD. I've copied standard layout SAPFMPL02 to applied with my FM Masters (no Grant & no Funded Program). When I use the layout with Entry_Free option the layout can be overview to be able to input the planning amount. Wh

  • Cannot logon to a new instance with SAP*

    We installed a ECC60 but unfortunatelu we loose the psw used during sapinst. THis psw has been used for all the users, included the SAP* and DDIC* users. Now the installation is finished but we are not able to logon in SAP. We deleted the rows for SA