Cross tab using sql

Hi,
I am using oracle 11g version.
I have a reporting requirement where in I have to produce a cross tab as explained below. Please help me in writing an SQL query to achieve this. Many thanks.
Sample data:
Customer             product type
AAA                           DVD
AAA                           Tape
BBB                           Tape
CCC                                 DVD
CCC                           Bluray
DDD                           DVD
DDD                           Tape
DDD                           Bluray
Logic
     AAA                                              BBB                         CCC                         DDD          
     DVD     Tape     Bluray                    DVD     Tape     Bluray               DVD     Tape     Bluray               DVD     Tape     Bluray
DVD          1                    DVD                         DVD               1          DVD          1     
Tape     1                         Tape          1               Tape                         Tape     1          1
Bluray                              Bluray                         Bluray     1                    Bluray          1                                                                                                    Final Output
No. of customers who purchased the products across all product types
     DVD     Tape     Bluray               
DVD          2     1               
Tape     2     1     1               
Bluray     1     1                    
Scripts:
create table cust_product(customer varchar2(5), product_type varchar2(10));
insert into cust_product values('AAA','DVD');
insert into cust_product values('AAA','Tape');
insert into cust_product values('BBB','Tape');
insert into cust_product values('CCC','DVD');
insert into cust_product values('CCC','Bluray');
insert into cust_product values('DDD','DVD');
insert into cust_product values('DDD','Tape');
insert into cust_product values('DDD','Bluray');

Hi,
858747 wrote:
... Sample data:
Customer             product type
AAA                           DVD
AAA                           Tape
BBB                           Tape
CCC                                 DVD
CCC                           Bluray
DDD                           DVD
DDD                           Tape
DDD                           Bluray...
Final Output
No. of customers who purchased the products across all product types
`     DVD     Tape     Bluray               
DVD          2     1               
Tape     2     1     1               
Bluray     1     1                    
Sorry, I don't follow the logic. Try explaining in words, with specific examples.
Didn't 2 distinct customers, 'CCC' and 'DDD', buy both 'DVD' and 'Bluray'? Why aren't the results
`     DVD     Tape     Bluray               
DVD          2     2
Tape     2     1     1               
Bluray     2     1                    with 2's in the corners?
Assuming that was just mistake, you can do something like this:
WITH     got_pairs     AS
     SELECT       a.product_type               AS product_a
     ,       NVL (b.product_type, a.product_type)     AS product_b
     FROM            cust_product     a
     LEFT OUTER JOIN     cust_product     b  ON  a.customer     = b.customer
                            AND     a.product_type != b.product_type
SELECT       *
FROM       got_pairs
PIVOT       (     COUNT (*)
       FOR     product_b
       IN     ( 'DVD'
          , 'Tape'
          , 'Blueray'
ORDER BY  CASE  product_a
          WHEN  'DVD'     THEN  1
          WHEN  'Tape'     THEN  2
          WHEN  'Bluray'     THEN  3
       END
;This assumes that the combination (customer, product_type) is unique, as it is in your sample data., and that the only product_types are the 3 in your sample data.
if those assumptions are not true, then post some revised sample data and results, that show what you want in those cases.
Sorry, I don't have an Oracle 11 database right now to test this.
I can (and did) test the outer join, that combines a product_type with itself only if it can't be combined with anything else.
Using a pre-Oracle 11 pivot technique, the following works:
WITH     got_pairs     AS
     SELECT       a.product_type               AS product_a
     ,       NVL (b.product_type, a.product_type)     AS product_b
     FROM            cust_product     a
     LEFT OUTER JOIN     cust_product     b  ON  a.customer     = b.customer
                            AND     a.product_type != b.product_type
SELECT       product_a     AS product_type
,       COUNT (CASE WHEN product_b = 'DVD'    THEN 1 END)     AS dvd
,       COUNT (CASE WHEN product_b = 'Tape'   THEN 1 END)     AS dvd
,       COUNT (CASE WHEN product_b = 'Bluray' THEN 1 END)     AS dvd
FROM       got_pairs
GROUP BY  product_a
ORDER BY  CASE  product_a
          WHEN  'DVD'     THEN  1
          WHEN  'Tape'     THEN  2
          WHEN  'Bluray'     THEN  3
       END
;Notice that the sub-query got_pairs is the same in both queries.
Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful!
Edited by: Frank Kulash on May 29, 2011 4:05 PM
Added Oracle 9 query.

Similar Messages

  • How to create Cross Tab using Desktop

    Hi Everyone,
    We use Sundard Banner (Universities) with Discoverer.
    I would like to create a Cross tab
    | Final Grade
    |_______________________________
    Course Title|
    |
    |
    Valid grade values are: HP - High Honors
    H - Honors
    P - Passed
    Suppose we had 3 students for class: Emergency Medicine
    George Washington - HP
    John Adams - HP
    Abraham Lincoln - H
    Would like query to look like this:
    | HP, | H | P
    |_________ |_____|_________________
    Emergency Medicine| 2 | 1
    |
    |
    Can this be done using Desktop, pls advise... thx, Sandra

    Hi Rod,
    Thx for your help.... I think I got it to work... Can I run the steps by you:
    a) create table query with: course title, final grade, count of final grade
    b) duplicated query as cross tab
    c) dragged course title to left
    d) noticed that Discoverer create a "field" - called data point for: count of final grade
    e) delete all vertical fields and just left count of final grade
    quests, please:
    ===========
    1) I tried a few times to create a cross tab before posting quest, and this is the first time that I see that
    Discoverer automatically created a field called datapoint for count of final grade. Do you have to follow
    a crosstab workflow carefully to the data point field to be created?
    2) what is definition of data point?
    3) Please confirm: The data point is located in the white space of the cross tab?
    4) Please confirm: When running the query, the values of final grades run across the top,
    including "blank" column for null value
    5) If (4), there is a column to tabulate rows with null values, why is the value 0, instead of an actual row count
    6) Under the various column values, is the name of the datapoint field running as a second heading row
    EH | H | HP
    Final_Grade Count | Final_Grade Count | Final_Grade Count | Final_Grade Count
    I will try to paste 3 screen shots below, using the "Plain text Help" box to the right of the screen
    thx again for your help. sandra

  • Formula/manual cross tab help

    my variable name in my database is rsq01. the results for this variable are 0,1,2,3,4,5.
    I need to setup a crosstab that only shows the results 1-5 and what percent of the total results they are, 0 needs to be excluded
    from the crosstab and from the count that is used in figuring the percentage because 0 is actually null.
    I have been told to do this I will have to make a manual cross tab using formulas.
    Any suggestions/examples on how to do this? Thanks.

    Pretty simple actually. Just create 5 formulas...
    //Formula 1
    Global NumberVar rsq01;
    IF rsq01= 1 THEN {TableName.FieldName} ELSE 0
    //Formula 2
    Global NumberVar rsq01;
    IF rsq01 = 2 THEN {TableName.FieldName} ELSE 0
    //Formula 3
    Global NumberVar rsq01;
    IF rsq01= 3 THEN {TableName.FieldName} ELSE 0
    //Formula 4
    Global NumberVar rsq01;
    IF rsq01= 4 THEN {TableName.FieldName} ELSE 0
    //Formula 5
    Global NumberVar rsq01;
    IF rsq01= 5 THEN {TableName.FieldName} ELSE 0
    Then group by the appropriate field, sum each of the formulas and hide the details.
    HTH,
    Jason

  • Help with Cross-tab

    Hello everyone...
    Here is some quick background info on my project:
    1) I am attempting to write a Crystal Report (version 10) to automatically capture crime statistics for a previous time period based on a current time period entered into the Crystal Report parameter. The current date range to automatically be captured is the previous seven weeks. For example, if a user enters the date range of June 15, 2008 - August 2, 2008, the Crystal Report will automatically gather data for the two date ranges of April 27, 2008 - June 14, 2008 (the previous date range) and June 15, 2008 - August 2, 2008 (the current date range). The purpose of this is to automatically gather crime statistics for two equal date ranges to compare crime rates.
    2) I have been able to successfully construct a formula to gather the previous date range.
    3) I have constructed a cross-tab but I am having difficulties formatting the cross-tab to display data as I desire.
    With the background of my project now described I will move into the main problem I am experiencing. I am able to display the data for all the necessary weeks in the cross-tab; using the same date range above I am able to show data for the fourteen weeks of April 27, 2008 - August 2, 2008. However, I wish to have a single cross-tab display the grand totals for just the previous date range while having weekly totals and a grand total for the current date range.
    Using the same date ranges above as an example, the date range of April 27, 2008 - June 14, 2008 will show just the grand totals for all seven weeks of that period. Conversely, I would like to have the date range of June 15, 2008 - August 2, 2008 show weekly totals as well as grand totals for all seven weeks of that period.
    I would like to keep all this data in a single cross-tab due to having to put the data in another crime analysis report.
    Any help you can provide is most appreciated...let me know if I can provide further info. Just so you know I am a bit of a beginner when it comes to Crystal Reports.

    Hello, you might try this:
    1) Create a formula field in your details section with this:
    Whileprintingrecords;
    If (table.date >= "start date of your pre-date range" and
    table.date <= "end date of your pre-date range") then 'Pre-Date'
    else
    if (table.date >= "your 1st week start" and table.date <= "your 1st week end") then 'Week 1'
    else (if table.date >= "your 2nd week start" and table.date <= "your 2nd week end") then 'Week 2'
    else .... for the 7 weeks you want a separate column.
    2) create the cross-tab and put the formula field as the column.
    3) I believe if you right-click on the total field to the far right and "Format Field" you can use the "Display String" option to delete the sum of the previous week's from the CurrentFieldValue and use the TOTEXT() function to display it. This will only display the sum of your current 7 weeks.
    You may want to go change the "Group Options" for the column to Sort in "Specified Order" and create named groups for each of your column headings. I can explain how you would do this if you need it.

  • Cross tab SQL

    hi all , im a beginner in SQL and just discovering oracle and Java so i made a small database : 1 table
    and i did the Database connectivity with my platform Java ( Netbeans) and every thing was okay.
    i started looking for how to create a cross tab between 2 elements from my table but i couldn't find the SQL script to do it
    my table is :
    ID--NAME--SURNAME--LOCATION---GRADE
    i want to have a cross tab between locations and the grade which calculatin the count of ID in each field so to create the interface in java so any help plz
    i know its somethin classic but im just a new beginner and im trying to create a simple database application
    i USE ORACLE 10G XE and NETBEANS
    thnxx

    Hello,
    welcome to the Oracle forums. This is the forum for the tool "SQL Developer". Questions about SQL and PL/SQL have their own forum at PL/SQL
    Best Regards
    Marcus

  • Cross tab data is getting multiplied if i use multiple queris in asingle report

    HI,
      i am using multiple queris for displaying data and graphs(charts).
      my requirement is to display 2 charts and data in crosstab in a single report.
      all the three thing (2charts and crosstab) will use diffrent values.
    I am writing 3 sql queries for getting appropriate values for charts and crosstab.
      Now the problem, both charts and crosstab are taking the values of all 3 queris
    i.e if i added crosstab  first to the report values are coming correctly. After  that if i add graph cross tab values are getting changed and graph values are not getting properly.
    if i add graph first then its coming correctly.
    if i tried to add all 3 components then values are going cores...... ?

    When you say you are writing 3 sql queries what do you mean? Are you creating 3 SQL command objects in the database expert? If so this is your problem, Crystal will pull a cartesian product through (this is every possible combinatin of rows from the 3 queries).
    If your 2 graphs and 1 crosstab are based on different datasets the way to approach this is to create each on a seperate report, then create a new blank report and add each of your 3 reports as subreports in the report footer.
    Hope this helps,
    Toby

  • How create SQL for Cross tab in template

    Hi,
    I have been starting to build data templates using SQL to select the data I require. I noticed in the word template-building tool there is an option to create cross tab table. I have tried looking at the standard documentation. I have been unable to work out how I should structure the SQL in my data template to allow me to create a cross tab table in the template?
    Thanks,
    Mark

    Post Author: SunilKanta
    CA Forum: General
    Yes, I had done exactly the same but when tried to display the subreport in new page, some portion of the cross tab is displayed. The page width is not increased proportionately.
    i have passed that sub report in footer of main report.
    But when i overlap this sub report with other cross tabs already present in the main report i can see full width view of sub report.

  • Is there a limit to no. of summary fields that can be used in a cross tab?

    Hi,
    While creating a cross tab is there a limitation to number of summarized fields that can be used?
    - The cross tab when uses 184 fields as summary fields leads to Crystal report application to crash at the time of export to excel.
    - Tried with two Datasources: XML and excel
    - If we reduce the number of summary fields used to 102 exactly, export works fine in excel.
    - If 2 cross tabs are used each containing 92 summary fields(in order to show 184) export to excel works fine.
    Please let me know if there is any such limitation which leads to CR application to crash when exporting in excel?
    Thanks
    Regards,
    Nidhi

    I suggest you purchase a case and have a dedicated support engineer work with you directly:
    http://www.sdn.sap.com/irj/boc/gettingstarted
    Or
    http://store.businessobjects.com/store/bobjects/Content/pbPage.CSC_map_countyselector/pgm.67024400?resid=jFmmLgoBAlcAAALO-iYAAAAP&rests=1278687224728
    If this is a bug you'll get a refund, if not post your enhancement request in the Idea Place. Or the Rep will suggest a better way to create your report.

  • How do I use a Cross-Tab to show me multiple fields without Summaries?

    Post Author: lindad
    CA Forum: Charts and Graphs
    Is it possible to add a Cross-Tab to a report with 6 columns and 4 rows; the values in each field are taken from a different field in the db and no summaries are used?
    Essentially the cross-tab needs to look like a table that you would create in Excel or Word.

    Post Author: Manuel de Kleine
    CA Forum: Charts and Graphs
    Linda,You cannot do that, because cross-tabs have always a summary on the axes (the number of having the value in the column AND the value in the row).If you need a table, you can use borders for your field and field header.

  • How to put report title and page no to appear in multiple pages,when using cross tab reports

    Post Author: shaminranaweera
    CA Forum: General
    I am using crystal reports 9.0 with odbc foxpro database conectivity
    I have designed a cross tab report and it is on the report header part and all the report details  are fine,except that the report title and  and page no's only show on the first page of my report.Pls tell me how can i put my report title and page no on all the pages in my crosstab.

    Post Author: foghat
    CA Forum: General
    You need to put your title in the page header if you want it to appear on every page.  The report header only displays once per report.

  • Problem using a conditional suppress in a cross-tab ?

    is there a problem using a conditional suppress in a cross-tab on a row  or summarized field  in crystal XI?
    I am using the following conditional suppress on a summarized field and its rows
             If {@SortCode}=4 then true;
    Sortcode is a group sorting formula field
    the summarized field is a formula field as well.
    All of the summarized fields are suppressed although the cross- tab performs correctly on @Sortcode  and the summarized field when not using the condition        
    it seems to me to be a reporting flow issue although i've included "whileprintingrecords" and "evaluateafter" with no success.
    i have also moved the cross-tab from the report header to group header and applied a conditional suppress on the group header through section expert.
    this supresses the group i dont want but includes grand totals for each group and also varys the number of columns
    i can't filter on sortcode because one of the grand total calculations requires those records and a subreport or second cross-tab does not contain the same number of columns
    the cross-tab is necessary as a client may have columns spanning one to many pages
    thanks for your help

    Hi I have a similar problem,
    I have an clock in solution, where i have some dates with data such as, various entries for a date eg, 01/11/2010 1hr, 01/11/2010 3 hrs etc, 03/11/2010 2hrs , 05/11/2010 4.5hrs, 05/11/2010 4 hrs so i need total for each day and highlight only those days, where total is less than 4.5, including days which donu2019t have records eg 02/11/2010 & 04/11/2010, I summarise in totals using a cross tab, to get summarised output for each day as,
                Totals
    01/11/2010    4
    03/11/2010    2
    05/11/2010    8.5
    in order to get the dates which didnu2019t have records, i added a dataset from Excel spreadsheet where i just have a sequential dates for the year , and use record selection to select only those dates in range which i need to display, so the result i get
    01/11/2010    4
    02/11/2010    0
    03/11/2010    2
    04/11/2010    0
    05/11/2010    8.5
    so far so good, all using cross tab, now i want to suppress rows which have total > 4.5 so the result should be
    01/11/2010    4
    02/11/2010    0
    03/11/2010    2
    04/11/2010    0
    How can i do that?

  • Use of variables in cross tab

    Hi experts,
    Can anyone tell me how to use a variable in cross-tab?
    I am populating the crosstab from the columns of a table.
    I want to use a variable (say percentage of averages) which calculates for each month for any number of months the data has been generated.
    Ex: Demo is my table and contains two average fields - average1 and average2 generated once for each month.
    Now I want a variable which calcaulates for each month, their variance based on some formula like (average1-average2)/average1.
    I have created a variable which calculates according to the above formula but its value is getting repeated for each month (the value of the first month) . It is not giving me the value corresponding to each month.
    Request you to help me.
    Thanks,
    Roshan

    Hi,
    Thanks for the reply.
    I have the following data from the cross tab.
         Jan     Feb     March
    Average 1     25     35     50
    Average 2     20     20     35
    Average 3     15     10     25
    And i want to generate the following structure dynammically based on the number of months/quarters.
         Jan     Var %     Feb     Var %     March     Var %
    Average 1     25          35          50     
    Average 2     20     20     20     42.85     35     30
    Average 3     15     40     10     71.42     25     50
    The new columns in the crosstab display should be dynamically generated.
    Request you to help me generate the new columns and the values.
    I have created this table in MS-Excel for reference.
    Thanks,
    Roshan

  • Exporting Cross-Tab to Excel using RAS 9.0 - incorrect and data loss

    Hello,
    Hope somone can help to solve the following issue.
    Develop a cross-tab report using Crystal Report Developer 9.0. service pack 5 or above.
    (1). Viewing in Crystal Report - no problem - all rows and columns displayed correctly.
    (2). Export to Excel using Crystal Report - no problem - all rows and columns exported correctly.
    (3). Viewing in RAS 9.0 - no problem, all rows and columns displayed correctly.
    (4). Export to Excel using RAS 9.0 - problem - only one or two rows with last rows are exported but wrong data. Most columns are not exported.  Seems like exporting errors.
    RAS 9.0 was patched with hotfix 200603 and service pack 5.
    Please help or is there any hotfix or service pack that resolved this problem?  As developer, we can use crystal report for exporting but for users, their only choice is through RAS.
    Thank you very much!

    Please re-post if this is still an issue to the .NET Development - Crystal Reports Forum or purchase a case and have a dedicated support engineer work with you directly

  • How to create cross tab reports using RAS SDK api with Crystal Reports XI

    Hi Everybody,
    Iam generating reports in a web-based application with Crystal Reports XI using Report Application Server(RAS) SDK API. The columns in my report exceed that of an A4 sized page. So, when I export that report to pdf, only those columns that fit to a page are showing up. To solve, this problem, I thought of using cross tab. But, I donot know how to generate cross tab report using RAS SDK API. I have tried to get some code from the internet. But, I did not find any java code for that.Can some one give me some sample code.It is very urgent.
    Thanks in advance.

    Hi,
    The easiest way I use is to create the worksheet as regular table and then when i verify the data I get (non aggregate) I duplicate it as a cross tab.
    In the duplication wizard I just need to define the axis (using drag and drop).
    if you want to create a cross tab from the beginning you need to define that in the new workbook wizard (check the "cross tab" rather then "table"), chose your fields and define the place you want them.
    The data point (the center of the cross tab) is aggregated as to your machine definition and will happen automatically.
    for example: to find the amount of receipt by months:
    On the left put the "Buyer Name", on top put the "Months" and in the data point put the amount.
    What you'll get is something like:
    months: jan feb mar apr ......
    buyer_name
    jhon_smith 100 50 30 250 ......
    jhon_doe 80 45 90 453 ........
    and so on.....

  • Array in formula to use in a cross-tab

    Post Author: eliasc
    CA Forum: Formula
    I am using CR 10.  I have a report where I am using a formula to use as a column header for a cross-tab.  Below is an example of what I am trying to achieve.
    ATLANTA INVOICE  ATLANTA SERVICE  ATLANTA WARR.  BIRMINGHAM INVOICE BIRMINGHAM SERVICE BIRMINGHAM WARR.  ETC..
    Below is the array in my formula.
    Shared NumberVar i;Shared StringVar CompanyName;Shared StringVar Array Companies := &#91;"HFSE - FW","ATLANTA INVOICE","ATLANTA SERVICE","ATLANTA WARR.","BIRMINGHAM INVOICE","BIRMINGHAM SERVICE","BIRMINGHAM WARR.","BGSI INVOICE","BGSI SERVICE","BGSI WARR.","PEN INVOICE","PEN SERVICE","PEN WARR.","JACKSON INVOICE","JACKSON SERVICE","JACKSON WARR.","FORT WORTH INVOICE","FORT WORTH SERVICE","FORT WORTH WARR.","JAX INVOICE","JAX SERVICE","JAX WARR.","LOUISVILLE INVOICE","LOUSIVILLE SERVICE","LOUISVILLE WARR.","OKLAHOMA CITY INVOICE","OKLAHOMA CITY SERVICE","OKLAHOMA CITY WARR."&#93;;0;
    local stringvar tString;shared numbervar CompName;
    CompName :=UBound(Companies) +1;i := CompName;
    For i := 1 to CompName step 1 do(  ReDim Preserve Companies&#91;i&#93;;    tString :=Companies&#91;i&#93; );
    tString;
    Can someone please help me.  I don't know where I am going wrong and why it isn't putting the above names in the cross-tab columns.
    Thank you for your help.
    Chris

    Hi,
    The "buffer" variable in DIG_Block_Out is an array of short integers (16 bit integers). It expects you to pass the array pointer as the function value. In the example below, "buffer" would be the parameter value.
    Dim buffer(5) as Integer
    Ron

Maybe you are looking for

  • Error message when trying to disconnect ipod

    I just got my ipod yesterday and I kept getting the do not disconnect message on the screen. I finally figured out that I had to disconnect it. When I did I got a message saying the ipod couldn't ejected because it contains that are in use by another

  • Iphoto 6 to iphoto 9 on Mac OS X

    I have a Mac OS X (10.4.11) with iphoto 6, is it possible to upgrade to iphoto 9 without losing my existing pictures. (I do not upgrade often)

  • Default value at ME21N

    Hi i want account assignment 'K' and item catagory 'D' get default if user selects perticular document type while creating Purchase order. if PO creation date is greater than a perticular date it should be applicable. screen field account assignment

  • Adding 7906 to CCM 4.1(3)SR3B

    I am trying to add a 7906 into our environment but the 7906 isn't in the "Add Phone" drop down list, has anyone else this? I have run cmterm-7911_7906-sccp.8-0-4SR1.exe on our callmanagers but it doesn't change the list.

  • ROWCOUNT IN THE TABLE

    Hi All, Let us assume, i have 10 tables in a schema "XYZ". Now i would like to know the 10 tablenames along with the rowcount in the 10 tables. like, TABLENAME COUNT OF ROWS TABLE A 150 TABLE B 1000 TABLE C 3000 TABLE D 20 please help me with the cod