Help, Pivot SQL

I am doing a report for a book store. We have data like:
STORE_ID SUBJECT     SUB_DETAIL     NUMBERS
1001     CD     CD_TITLE1     2
1001     CD     CD_TITLE2     4
1001     CD     CD_TITLE3     1
1001     DVD     DVD_TITLE1     7
1001     DVD     DVD_TITLE2     5
1001     DVD     DVD_TITLE3     3
1001     DVD     DVD_TITLE4     2
1001     BOOK     BOOK_TITLE1     6
1001     BOOK     BOOK_TITLE2     2
1001     OTHERS     OTHERS1     9
1001     OTHERS     OTHERS2     1
1001     OTHERS     OTHERS3     8
1001     OTHERS     OTHERS4     2
1001     OTHERS     OTHERS5     3
We want to display the data like:
STORE_ID CD CD_NUM DVD DVD_NUM BOOK BOOK_NUM OTHERS     OTHERS_NUM
It can not show the format I want.
Thanks a lot for any help!
Jeanne

nikos101 wrote:
> How would change this query to display a table like:
Do you *HAVE* to change the query... you could just display
it in the
desired format if that it the ultimate and only goal.
<table>
<tr>
<td>name</td>
<td>amount</td>
</tr>
<cfoutput query="sumQry">
<tr><td>Rates</td><td>#rates#</td></tr>
<tr><td>Conversion</td><td>#conversion#</td></tr>
</cfoutput>
</table>

Similar Messages

  • PIVOT sql help

    Hi again
    I need some PIVOT sql help
    In this query:
    SELECT
    SUM([RATES]) as RATES
    ,SUM([CONVERSION])as CONVERSION
    FROM REPORTING
    outputs
    RATES CONVERSION
    23 234
    How would change this query to display a table like:
    Name Amount
    RATES 23
    CONVERSION 234
    Keep up the good work !

    nikos101 wrote:
    > How would change this query to display a table like:
    Do you *HAVE* to change the query... you could just display
    it in the
    desired format if that it the ultimate and only goal.
    <table>
    <tr>
    <td>name</td>
    <td>amount</td>
    </tr>
    <cfoutput query="sumQry">
    <tr><td>Rates</td><td>#rates#</td></tr>
    <tr><td>Conversion</td><td>#conversion#</td></tr>
    </cfoutput>
    </table>

  • Need help in SQL (DENSE_RANK) function

    Hello All,
    I need the help in SQL.
    We have a table called status and the column are
    status_id number
    account_id number
    status_cd varchar2(10)
    created_id varchar2(10)
    created_by date
    and data is as follows
    insert into status values (1,101,'ENTER','ABC',to_date('21-JAN-2007 11:15:14','DD-MON-YYYY HH:MI:SS'));
    insert into status values (2,101,'REVIEW','DEF',to_date('21-JAN-2007 11:30:25','DD-MON-YYYY HH:MI:SS'));
    insert into status values (3,101,'APPROVE','GHI',to_date('21-JAN-2007 11:30:25','DD-MON-YYYY HH:MI:SS'));
    insert into status values (4,102,'ENTER','ABC',to_date('21-JAN-2007 11:18:14','DD-MON-YYYY HH:MI:SS'));
    insert into status values (5,102,'REVIEW','DEF',to_date('21-JAN-2007 11:33:25','DD-MON-YYYY HH:MI:SS'));
    insert into status values (6,102,'CANCEL','GHI',to_date('21-JAN-2007 11:33:25','DD-MON-YYYY HH:MI:SS'));
    insert into status values (7,103,'ENTER','ABC',to_date('21-JAN-2007 11:21:14','DD-MON-YYYY HH:MI:SS'));We have different status as follows
    1. ENTER
    2. REVIEW
    3. APPROVE
    4. CANCEL
    5. REJECT
    My requirement ..
    I need the max of created_id column for the status in ('APPROVE','CANCEL') and if there is no status in ('APPROVE','REVIEW') than it should be NULL.
    I wrote an SQL as
    select account_id,max(created_id) keep (dense_rank first order by decode(status_cd,'APPROVE',created_dt,'REVIEW',created_dt,NULL) DESC NULLS LAST,
          decode(status_cd,'APPROVE',status_id,'REVIEW',status_id,NULL) DESC NULLS LAST) last_app_rev_user
    from status
    group by account_id and gives me the output like
    ACCOUNT_ID LAST_APP_R
           101 GHI
           102 DEF
           103 ABCBut I want the Output like
    ACCOUNT_ID LAST_APP_R
           101 GHI
           102 DEF
           103 NULLAs the account 103 has no status called 'REVIEW' and 'APPROVE'
    My DB Version in 10.2.0.3.0.
    Hope I explain it properly. And if you have any other option without dense_rank still i will be happy.
    Thanks in advance for your help.
    AB
    null
    Message was edited by:
    AB

    instead of max(created_id) keep... use
    smth like max(case when status_cd in ('APPROVE','REVIEW') then created_id end) keep...

  • Help in SQL Developer

    Is there any context-sensitive help in SQL Developer. I'm looking for a way to link SQL syntax with some sort of a Help function. Searching the SQL Reference pdf just doesn't cut it. For example, when I search the SQL Reference pdf for Round, I get 134 hits. I would look for a page or 2 on how to use Round, with examples, but accessible directly from SQL Developer.

    No there isn't.
    There's a rejected feature request for this at the Exchange (http://htmldb.oracle.com/pls/otn/f?p=42626:39:947182819474243::NO::P39_ID:5662), so chances are very small it ever makes it in.
    Nevertheless, you can still vote and add comments there; if there's enough weight on an item it will eventually make it for the TODO list.
    Including the doc isn't necessary, but just linking to the correct page would save a lot of time. In the case of ROUND, on pressing F1 inside the code editor or worksheet, sqldev could link directly to the SQL reference (http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/functions135.htm).
    If the team doesn't want to put it in, maybe someone else does. It would make a nice extension... if you feel up for it?
    K.

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, 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_Number, Invoice_Type, Vendor_Number. When there are no multiple 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-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

  • Accessing online help in Sql developer

    For some reason I have lost the ability to access Help in Sql Developer. Nothing happenx when I click on the "Table of Contents" in the Help menu. I un and re installed Sql Developer, but thie problem remains.
    My OS is vista 32 bit.
    Thanks
    Mewbie

    There's a +\sqldeveloper\system1.5.1.54.40\o.ide.11.1.1.0.22.49.42\windowinglayout.xml+ under your user profile. Deleting that should revert illegal positions (as it may have got pushed off screen).
    You can also delete the whole +\sqldeveloper+ folder (or selective subfolders) to reset everything to factory defaults...
    Hope that helps,
    K.

  • Can u give an detail examples or help on SQL- loader

    Can u give an detail examples or help on SQL- loader
    I need full details on this how to run and what are the pre requirements for this and what
    Can u give an example with unix+sql loader

    The Oracle Utilities manual has a chapter on SQL*Loader Case Studies
    http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96652/ch10.htm#1656
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Help with SQL to Pivot SQL

    I have requirment to build the SQL to Merge rows value to a single value.
    Here is the Data
    TABLE_A
    ID SEQ MESG
    1 1 MSG1
    1 2 MSG2
    2 1 MSG1
    3 1 MSG1
    3 2 MSG2
    3 3 MSG3
    I need output as
    ID MSG
    1 MSG1 MSG2
    2 MSG1
    3 MSG1 MSG2 MSG3

    Create function like below:
    CREATE OR REPLACE  FUNCTION rowtocol( p_slct IN VARCHAR2, p_dlmtr IN VARCHAR2 DEFAULT ',' ) RETURN VARCHAR2
    AUTHID CURRENT_USER AS
        TYPE c_refcur IS REF CURSOR;
        lc_str VARCHAR2(4000);
        lc_colval VARCHAR2(4000);
        c_dummy c_refcur;
        l number;
    BEGIN
        OPEN c_dummy FOR p_slct;
        LOOP
        FETCH c_dummy INTO lc_colval;
        EXIT WHEN c_dummy%NOTFOUND;
        lc_str := lc_str || p_dlmtr || lc_colval;
        END LOOP;
        CLOSE c_dummy;
        RETURN SUBSTR(lc_str,2);
           EXCEPTION
           WHEN OTHERS THEN
              lc_str := SQLERRM;
              IF c_dummy%ISOPEN THEN
              CLOSE c_dummy;
              END IF;
           RETURN lc_str;
    END;
    /And print result like :
       SELECT DISTINCT  a.job,
          rowtocol(  'SELECT ename  FROM emp
                           WHERE
                           job = ' || '''' || a.job || '''' || ' ORDER BY ename'
         AS Employees
        FROM emp;

  • Pivot sql year/month/category

    Need help with this :
    Requirement : need to pivot data based on year, month and display the sales correctly. if the data for any month does not exist that month shoudl not appear in the results.
    Sample data :
    --DROP TABLE APPS.TEST_OM_V CASCADE CONSTRAINTS;
    CREATE TABLE APPS.TEST_OM_V
    TAX_CATEGORY VARCHAR2(250 BYTE),
    SHIP_FROM_ORG_NAME VARCHAR2(100 BYTE),
    SCHEDULE_SHIP_DATE DATE,
    UNIT_SELLING_PRICE NUMBER,
    ORDERED_QUANTITY NUMBER,
    INVOICED_SALES NUMBER
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('Operating Supplies', 'DC FONT (FONT-120)', TO_DATE('02/01/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 12, 13,
    23);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('09/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 90, 7,
    23.34);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC Florida (FLO-180)', TO_DATE('09/14/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 8,
    75);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('10/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 2,
    100.11);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('08/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 2,
    75);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('Operating Supplies', 'DC DIST (DIS-130)', TO_DATE('10/21/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 12, 13,
    23);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('08/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 2,
    75);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('Operating Supplies', 'DC CANADA (CAN-180)', TO_DATE('01/02/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 23, 1,
    45);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('Operating Supplies', 'DC PACK (PK-160)', NULL, 1, 2,
    1);
    COMMIT;
    Expected result , or anything close to this :
                                                                                2011                                     2012
                                                                   AUG      SEP          OCT         JAN   FEB      UNSCHEDULED
      COFFEE
                                    DC CANADA (CAN-180)          -30         606.66    -40.11         0          0          0
                                    DC Florida (FLO-180)          0           165         0           0          0          0
    Operating Supplies
                                    DC CANADA (CAN-180)           0           0            0         -22        0          0
                                    DC DIST (DIS-130)             0           0            133         0         0          0
                                    DC FONT (FONT-120)            0           0            0           0         133        0
                                    DC PACK (PK-160)              0           0            0           0          0           1 I tried grouping and summing and then lost my way...
    select TAX_CATEGORY, SHIP_FROM_ORG_NAME, nvl(TO_CHAR((SCHEDULE_SHIP_DATE), 'MM/YYYY'),'N/A') SCHEDULE_SHIP_DATE,
    sum((unit_selling_price * ORDERED_QUANTITY ) - nvl(INVOICED_SALES,0)) CARRYOVER
    from XXCNC.TEST_OM_V where 1=1
    group by TAX_CATEGORY, SHIP_FROM_ORG_NAME,nvl(TO_CHAR((SCHEDULE_SHIP_DATE), 'MM/YYYY'),'N/A')
    order by 1,2,3;
    Thanks for your help in advance.
    J

    Like this?:
    SQL> set num 6 lin 120 trims on
    SQL> col tax_category for a20
    SQL> col SHIP_FROM_ORG_NAME for a32
    SQL> break on tax_category
    SQL> SELECT *
      2  FROM (SELECT tax_category,
      3               ship_from_org_name,
      4               NVL( TO_CHAR( ( schedule_ship_date ), 'MM/YYYY' ), 'N/A' ) schedule_ship_date,
      5               ( unit_selling_price * ordered_quantity ) - NVL( invoiced_sales, 0 ) carryover
      6        FROM test_om_v) PIVOT (SUM( carryover )
      7                        FOR schedule_ship_date
      8                        IN  ('08/2011' AS "Aug'11",
      9                            '09/2011' AS "Sep'11",
    10                            '10/2011' AS "Oct'11",
    11                            '11/2011' AS "Nov'11",
    12                            '12/2011' AS "Dec'11",
    13                            '01/2012' AS "Jan'12",
    14                            '02/2012' AS "Feb'12",
    15                            'N/A' AS "UNSCHEDULED"))
    16  ORDER BY 1, 2, 3
    17  /
    TAX_CATEGORY         SHIP_FROM_ORG_NAME               Aug'11 Sep'11 Oct'11 Nov'11 Dec'11 Jan'12 Feb'12 UNSCHEDULED
    COFFEE               DC CANADA (CAN-180)                 -30 606.66 -40.11
                         DC Florida (FLO-180)                       165
    Operating Supplies   DC CANADA (CAN-180)                                                    -22
                         DC DIST (DIS-130)                                 133
                         DC FONT (FONT-120)                                                            133
                         DC PACK (PK-160)                                                                            1
    6 rows selected.:p
    Edited by: LKBrwn_DBA on Dec 16, 2011 12:18 PM

  • Need help on sql

    Hello Everyone,
    I have a req where the output should be below format.My data like this.. Now I want the cust_no to be a single row instead of two lines. I am not adding status column in the query but the amount and reduced amount are calculated based on Status field using CASE statement. I am thinking of using pivot to achieve this but don’t know how to
    Cust_no
    Status
    Amount
    Reduced Amount
    12345
    Regular
    $50.26
    12345
    Discount
    $12
    22222
    Regular
    $233
    22222
    Discount
    $2
    Output
    Cust_no
    Amount
    Reduced Amount
    12345
    $50.26
    $12
    22222
    $233
    $2
    Can someone help me on this?
    Thanks

    This is a plain GROUP BY:
    with t as (
               select 12345 cust_no,'Regular' status,'50,26' amount,null reduced_amount from dual union all
               select 12345,'Discount',null,'12' from dual union all
               select 2222,'Regular','233',null from dual union all
               select 2222,'Discount',null,'2' from dual
    select  cust_no,
            sum(amount)amount,
            sum(reduced_amount) reduced_amount
      from  t
      group by cust_no
       CUST_NO     AMOUNT REDUCED_AMOUNT
          2222        233              2
         12345      50,26             12
    SQL>
    SY.

  • Need some help over sql query format

    Input :
    TABLE 1 ppl
    id name
    1 ravi
    2 andy
    3 john
    TABLE 2 fa_ppl
    id attr_name attr_value
    1 watch Guess
    1 laptop Sony
    2 fashion casual
    2 laptop Dell
    3 watch fossil
    3 fashion formal
    OUTPUT Required:(3 rows)
    name watch laptop fashion
    ravi guess sony NULL
    andy NULL dell casual
    john fossil NULL formal
    SQL Statements that may help in schema objects:
    create table ppl(id number,name varchar2(50));
    create table fa_ppl(id number,attr_name varchar2(20), attr_value varchar2(20));
    insert into ppl values(1,'ravi');
    insert into ppl values(2,'andy');
    insert into ppl values(3,'john');
    insert into fa_ppl values(1,'laptop','sony');
    insert into fa_ppl values(1,'watch','guess');
    insert into fa_ppl values(2,'laptop','dell');
    insert into fa_ppl values(2,'fashion','casual');
    insert into fa_ppl values(3,'fashion','formal');
    insert into fa_ppl values(3,'watch','fossil');
    I tried in the below way:
    Select P.name,
    case when attr_name='fashion' then attr_value end as fashion ,
    case when attr_name='laptop' then attr_value end as laptop,
    case when attr_name='watch' then attr_value end as watch,
    from ppl P join fa_ppl F on (P.id=F.id and F.attr_name in ('fashion','laptop','watch'))
    PROBLEM:
    Getting separate rows(6 rows in my case) for each attribute_value.
    Thanks a lot.....

    What you are trying is a pivot. There is a [url https://forums.oracle.com/forums/thread.jspa?threadID=2174552#9360005]thread in the FAQ linking to various methods.
    You are actually pretty close, if you just do a group by on your select:
    Select P.name,
    max(case when attr_name='fashion' then attr_value end) as fashion ,
    max(case when attr_name='laptop' then attr_value end) as laptop,
    max(case when attr_name='watch' then attr_value end) as watch
    from ppl P join fa_ppl F on (P.id=F.id and F.attr_name in ('fashion','laptop','watch'))
    group by
    p.nameBut if you have several people with same name, you probably want to do this:
    Select
    p.id, /*you may omit this column if you do not need it*/
    max(P.name) as name,
    max(case when attr_name='fashion' then attr_value end) as fashion ,
    max(case when attr_name='laptop' then attr_value end) as laptop,
    max(case when attr_name='watch' then attr_value end) as watch
    from ppl P join fa_ppl F on (P.id=F.id and F.attr_name in ('fashion','laptop','watch'))
    group by
    p.idSimilar can be done in 11G with the PIVOT statement. See the links in the FAQ thread.

  • Need help pivoting tables

    Hi Everyone,
    I have the following query which I would like to Pivot...
    DECLARE @1yrBegin DATE, @1yrEnd DATE
    , @2yrBegin DATE, @2yrEnd DATE
    , @3yrBegin DATE, @3yrEnd DATE
    SET @1yrBegin = GETDATE()
    SET @1yrEnd = DATEADD(YY, -1, GETDATE())
    SET @2yrBegin = @1yrEnd
    SET @2yrEnd = DATEADD(YY, -2, GETDATE())
    SET @3yrBegin = @2yrEnd
    SET @3yrEnd = DATEADD(YY, -3, GETDATE())
    SELECT *
    FROM
    /* Cube date: Today - 1 year to Today */
    SELECT
    T0.ItemCode AS 'Item Code'
    , T0.ItemName AS 'Item Name'
    , T0.U_SCE_IN_Industry AS 'Industry'
    , T0.OnHand AS 'SOH'
    , T0.StockValue AS 'Total Value'
    , ISNULL(CAST(CAST(SUM(T1.Quantity) AS decimal(10,2)) AS varchar), '') AS 'Qty Sold'
    , 'Qty Sold 1 Yr Ago' AS 'Duration'
    FROM AU.dbo.OITM T0
    LEFT JOIN SCE.dbo.AU_SALES_R T1 ON T1.ItemCode = T0.ItemCode COLLATE SQL_Latin1_General_CP850_CI_AS
    INNER JOIN SCE.dbo.AU_SALES_H T2 ON T2.DocEntry = T1.DocEntry
    WHERE T2.DocDate >= @1yrEnd AND T2.DocDate <= @1yrBegin
    GROUP BY T0.ItemCode, T0.ItemName, T0.U_SCE_IN_Industry, T0.OnHand, T0.StockValue
    UNION ALL
    /* Cube data: Today - 2 years to Today - 1 year */
    SELECT
    T0.ItemCode AS 'Item Code'
    , T0.ItemName AS 'Item Name'
    , T0.U_SCE_IN_Industry AS 'Industry'
    , T0.OnHand AS 'SOH'
    , T0.StockValue AS 'Total Value'
    , ISNULL(CAST(CAST(SUM(T1.Quantity) AS decimal(10,2)) AS varchar), '') AS 'Qty Sold'
    , 'Qty Sold 2 Yrs Ago' AS 'Duration'
    FROM AU.dbo.OITM T0
    LEFT JOIN SCE.dbo.AU_SALES_R T1 ON T1.ItemCode = T0.ItemCode COLLATE SQL_Latin1_General_CP850_CI_AS
    INNER JOIN SCE.dbo.AU_SALES_H T2 ON T2.DocEntry = T1.DocEntry
    WHERE T2.DocDate >= @2yrEnd AND T2.DocDate <= @2yrBegin
    GROUP BY T0.ItemCode, T0.ItemName, T0.U_SCE_IN_Industry, T0.OnHand, T0.StockValue
    UNION ALL
    /* Cube data: Today - 3 years to Today - 2 years */
    SELECT
    T0.ItemCode AS 'Item Code'
    , T0.ItemName AS 'Item Name'
    , T0.U_SCE_IN_Industry AS 'Industry'
    , T0.OnHand AS 'SOH'
    , T0.StockValue AS 'Total Value'
    , ISNULL(CAST(CAST(SUM(T1.Quantity) AS decimal(10,2)) AS varchar), '') AS 'Qty Sold'
    , 'Qty Sold 3 Yrs Ago' AS 'Duration'
    FROM AU.dbo.OITM T0
    LEFT JOIN SCE.dbo.AU_SALES_R T1 ON T1.ItemCode = T0.ItemCode COLLATE SQL_Latin1_General_CP850_CI_AS
    INNER JOIN SCE.dbo.AU_SALES_H T2 ON T2.DocEntry = T1.DocEntry
    WHERE T2.DocDate >= @3yrEnd AND T2.DocDate <= @3yrBegin
    GROUP BY T0.ItemCode, T0.ItemName, T0.U_SCE_IN_Industry, T0.OnHand, T0.StockValue
    ) AS CB
    ORDER BY CB.[Item Code], CB.Duration
    Below is a capture of some sample data returned by my query, and furthermore how I would like it to be presented
    As shown in the image above I would like to do away with the current 'Duration' column, and pivot my data such that the 'Qty Sold' is listed horizontally (rather than vertically) under the corresponding headings, 'Qty Sold 1 Yr Ago', 'Qty Sold 2 Yrs Ago',
    and 'Qty Sold 3 Yrs Ago'.
    Given that I know I am looking at only three years of past sales, and by extension only 3 rows being pivoted I figure that a static pivot should apply here. However as I am relatively new to SQL I am at a loss concerning how to perform the actual pivot.
    Any help here will be greatly appreciated.
    Kind Regards,
    David

    Try below , Not tested
    Refer
    http://technet.microsoft.com/en-in/library/ms177410(v=sql.105).aspx
    DECLARE @1yrBegin DATE, @1yrEnd DATE
    , @2yrBegin DATE, @2yrEnd DATE
    , @3yrBegin DATE, @3yrEnd DATE
    SET @1yrBegin = GETDATE()
    SET @1yrEnd = DATEADD(YY, -1, GETDATE())
    SET @2yrBegin = @1yrEnd
    SET @2yrEnd = DATEADD(YY, -2, GETDATE())
    SET @3yrBegin = @2yrEnd
    SET @3yrEnd = DATEADD(YY, -3, GETDATE())
    SELECT *
    FROM
    /* Cube date: Today - 1 year to Today */
    SELECT
    T0.ItemCode AS 'Item Code'
    , T0.ItemName AS 'Item Name'
    , T0.U_SCE_IN_Industry AS 'Industry'
    , T0.OnHand AS 'SOH'
    , T0.StockValue AS 'Total Value'
    , ISNULL(CAST(CAST(SUM(T1.Quantity) AS decimal(10,2)) AS varchar), '') AS 'Qty Sold'
    , 'Qty Sold 1 Yr Ago' AS 'Duration'
    FROM AU.dbo.OITM T0
    LEFT JOIN SCE.dbo.AU_SALES_R T1 ON T1.ItemCode = T0.ItemCode COLLATE SQL_Latin1_General_CP850_CI_AS
    INNER JOIN SCE.dbo.AU_SALES_H T2 ON T2.DocEntry = T1.DocEntry
    WHERE T2.DocDate >= @1yrEnd AND T2.DocDate <= @1yrBegin
    GROUP BY T0.ItemCode, T0.ItemName, T0.U_SCE_IN_Industry, T0.OnHand, T0.StockValue
    UNION ALL
    /* Cube data: Today - 2 years to Today - 1 year */
    SELECT
    T0.ItemCode AS 'Item Code'
    , T0.ItemName AS 'Item Name'
    , T0.U_SCE_IN_Industry AS 'Industry'
    , T0.OnHand AS 'SOH'
    , T0.StockValue AS 'Total Value'
    , ISNULL(CAST(CAST(SUM(T1.Quantity) AS decimal(10,2)) AS varchar), '') AS 'Qty Sold'
    , 'Qty Sold 2 Yrs Ago' AS 'Duration'
    FROM AU.dbo.OITM T0
    LEFT JOIN SCE.dbo.AU_SALES_R T1 ON T1.ItemCode = T0.ItemCode COLLATE SQL_Latin1_General_CP850_CI_AS
    INNER JOIN SCE.dbo.AU_SALES_H T2 ON T2.DocEntry = T1.DocEntry
    WHERE T2.DocDate >= @2yrEnd AND T2.DocDate <= @2yrBegin
    GROUP BY T0.ItemCode, T0.ItemName, T0.U_SCE_IN_Industry, T0.OnHand, T0.StockValue
    UNION ALL
    /* Cube data: Today - 3 years to Today - 2 years */
    SELECT
    T0.ItemCode AS 'Item Code'
    , T0.ItemName AS 'Item Name'
    , T0.U_SCE_IN_Industry AS 'Industry'
    , T0.OnHand AS 'SOH'
    , T0.StockValue AS 'Total Value'
    , ISNULL(CAST(CAST(SUM(T1.Quantity) AS decimal(10,2)) AS varchar), '') AS 'Qty Sold'
    , 'Qty Sold 3 Yrs Ago' AS 'Duration'
    FROM AU.dbo.OITM T0
    LEFT JOIN SCE.dbo.AU_SALES_R T1 ON T1.ItemCode = T0.ItemCode COLLATE SQL_Latin1_General_CP850_CI_AS
    INNER JOIN SCE.dbo.AU_SALES_H T2 ON T2.DocEntry = T1.DocEntry
    WHERE T2.DocDate >= @3yrEnd AND T2.DocDate <= @3yrBegin
    GROUP BY T0.ItemCode, T0.ItemName, T0.U_SCE_IN_Industry, T0.OnHand, T0.StockValue
    ) AS CB
    PIVOT
    SUM([Qty Sold])
    FOR Duration IN ([Qty Sold 1 Yr Ago], [Qty Sold 2 Yrs Ago], [Qty Sold 3 Yrs Ago])
    ) AS PivotTable;
    ORDER BY CB.[Item Code]

  • Help ! SQL Required

    Hi Experts,
    Using the details below in the table ADV_TAB, I need to generate the Report in the following Output Format :
    CREATE TABLE ADV_TAB
    PID          VARCHAR2(3),
    NOB          VARCHAR2(8),
    AMOUNT          NUMBER(15,2),
    TARGET          NUMBER(15,2),
    PURPOSE          NUMBER(5),
    MPURPOSE     VARCHAR2(30),
    PURPOSETYPE     VARCHAR2(35),
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '10029ABR', 200000, 0, 706, 'AH', 'SPECIAL' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '10109ABR', 150000, 0, 706, 'AH', 'SPECIAL' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '10286ABR', 200000, 0, 706, 'AH', 'SPECIAL' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '10567ABR', 300000, 0, 706, 'AH', 'SPECIAL' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '10603ABR', 500000, 0, 10207, 'KC', 'KISAAN' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '10900ABR', 500000, 0, 10207, 'KC', 'KISAAN' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '11179ABR', 450000, 0, 501, 'TR', 'TRACTOR' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '11446ABR', 200000, 0, 706, 'AH', 'SPECIAL' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '14006ABR', 60000, 0, 105, 'MI', 'MINOR' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '16169ABR', 1075000, 0, 306, 'LD', 'LAND' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '16179ABR', 1100000, 0, 306, 'LD', 'LAND' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '16192ABR', 500000, 0, 8104, 'RH', 'HOUSING' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'ABR', '', 0, 88000000, 0, '', '' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'AJN', '10636AJN', 250000, 0, 10207, 'KC', 'KISAAN' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'AJN', '10636AJN', 300000, 0, 306, 'LD', 'LAND' );
    INSERT INTO ADV_TAB ( PID, NOB, AMOUNT, TARGET, PURPOSE, MPURPOSE, PURPOSETYPE) VALUES ( 'AJN', '', 0, 39400000, 0, '', '' );
    OUTPUT FORMAT :
                     SPECIAL             KISAAN             TRACTOR            MINOR                  LAND               HOUSING            TOTAL          
    PID     TARGET          NOB     AMOUNT          NOB     AMOUNT          NOB     AMOUNT          NOB     AMOUNT          NOB     AMOUNT        NOB   AMOUNT          NOB     AMOUNT     
    ABR     88000000     5     1050000          2     1000000          1     450000          1     200000          1     60000        2      2175000     13     5435000
    AJN     39400000     0     0          1     2500000          0     0          0     0          1     300000        0      0          2     550000
    TOTAL->                                                                                                                                                      Can the above Report Format be generated using plain SQL ?

    Hi,
    this is a pivoting problem.
    Have you already checked in the FAQ: [url:https://forums.oracle.com/forums/thread.jspa?threadID=2174552#9360005]4. How do I convert rows to columns?
    It should be helpful also to mention which database version are you using to understand if it 11g PIVOT function can be used.
    Could you also tell me what you expect in the output for the row starting with
    TOTAL->     Regards.
    Al

  • HELP!   SQL Query:  Other ways to reorder column display?

    I have a SQL query report with a large number of columns (users can hide/show columns as desired). It would be great if the column display order could be changed by changing the order of the columns in the SELECT list in the Report Definition, but that doesn't work -- it puts changed or added columns at the end regardless of the order in the SELECT list of the query.
    Is there some other way to reorder the columns displayed without using the Report Attributes page? It's extremely tedious to move columns around using the up/down arrows which redisplays the page each time. Am I missing a way to change display order, or does anyone have a "trick" to do this? It's so painful....
    When defining forms you can reoder columns by specifying a sequence number for each column. Just curious as to why reports were not done the same way, and are there any plans to address this in a future release?
    Karen

    Yes, reordering columns is extremely painful.
    It is supposed to be much improved in the next version.
    See
    Re: Re-ordering columns on reports
    Moving columns up/down in Report  Attributes
    See my example at
    http://htmldb.oracle.com/pls/otn/f?p=24317:141
    Basically, let the users move columns around until they are blue in the face, provide a Save button to save the column order in a user preference and reorder the columns when the page reloads.
    Or you can use Carl's PL/SQL shuttle as the widget to specify the columns shown and their order. The shuttle is at http://htmldb.oracle.com/pls/otn/f?p=11933:27
    Hope this helps.
    Message was edited by:
    Vikas

  • Query help in sql commands

    using apex 4.1 i'm entering the following query in the sql command window and I keep getting a pop-up for Entering Bind Variable. I'm not using bind variables though, anyone else see this issue before?
    SELECT A.FIRST,A.LAST,A.COMPANY AS CNAME,
    J.TOT_MAN_HOURS,
    J.ACREAGE,
    W.NUM_WORKERS,
    W.START_DT
    FROM EW_ACCOUNTS A, EW_WORK_ORDER W, EW_JOBS J
    WHERE A.ID = J.ACCT_ID
    AND J.JOB_ID = W.JOB_ID
    AND W.START_DT >= SYSDATE
    AND W.START_DT < SYSDATE+1
    ORDER BY W.START_DT

    I tried that and it didn't seem to help either.
    Funny though, if I write a new query against just one of the tables and write out each column name. it works. If I use the * instead of writing each column name, I have the same issue.
    This is in apex.appshosting.com free demo environment. I sent them an email asking about it and they told me it was a code issue and they don't support the demo environment.

Maybe you are looking for

  • Cant update my iPod touch 4g to iOS 6

    help update my iPod touch 4g it always says iOS 5.1.1 Your Software Is Up To Date Please Help Me Even The iOS 6 Update Is Available

  • HP Printer Assistant is not working ...keeps loading...

    Hello, I have purchased a HP Officejet Pro 6830  All in One printer and have installed the software from the CD, installed updates and already used the HP Docter software but the Printer Assistant does not load. It keeps on with a blank screen, with

  • Set image path in java class library

    Hi, I created a java class library project and made .jar file. My java class library contains .jpg files in separete folder named as Images. My .jar file contains list of classes and image folder also but when i am using .jar file in applet. java cla

  • How to dump screen in Windows 7

    How to dump screen in Windows 7 environment. I cannot find the dump screen key on Macbook Air.

  • Tecra S1 blank laptop screen, but monitor plugged in works fine.

    Hi All, I have a problem with my S1 in that if I boot it up, nothing appears on the screen, no promt no loading screen nothing. However if I plug a monitor in it the display appears on the monitor (laptop screen will still be blank) if I press FN & F