How To Write A Matrix Query in Oracle 10g

Hi All,
I need to write a query displaying total of each Month and each quarter total. Here is example:
CREATE TABLE T_CUST_REG(
CUST_ID NUMBER,
CUST_NAME VARCHAR2(255),
REGDATE  DATE);
INSERT INTO T_CUST_REG VALUES (1, 'A','01-JAN-2012');
INSERT INTO T_CUST_REG VALUES (2, 'B','01-FEB-2012');
INSERT INTO T_CUST_REG VALUES (3, 'C','01-MAR-2012');
INSERT INTO T_CUST_REG VALUES (4, 'D','01-APR-2012');
INSERT INTO T_CUST_REG VALUES (5, 'E','01-MAY-2012');
INSERT INTO T_CUST_REG VALUES (6, 'F','01-JUN-2012');
INSERT INTO T_CUST_REG VALUES (7, 'G','01-JUL-2012');
INSERT INTO T_CUST_REG VALUES (8, 'H','01-AUG-2012');
INSERT INTO T_CUST_REG VALUES (9, 'I','01-SEP-2012');
INSERT INTO T_CUST_REG VALUES (10, 'J','01-OCT-2012');
INSERT INTO T_CUST_REG VALUES (11, 'K','01-NOV-2012');
INSERT INTO T_CUST_REG VALUES (12, 'L','01-DEC-2012');
Output REQUIRED:
JAN
FEB
MAR
Q1
APR
MAY
JUN
Q2
JUL
AUG
SEP
Q3
OCT
NOV
DEC
Q4
1
1
1
3
1
1
1
3
1
1
1
3
1
1
1
3
I am able to create matrix with following query, but issue is how to put Quarter(total) in between.
Select Count(1), TO_CHAR(REGDATE, 'MON') MON 
FROM T_CUST_REG T
GROUP BY TO_CHAR(REGDATE, 'MON');
Regards

Hi,
The query you posted will produce a separate row for each month, not a separate column.  Is that what you want?
If so, you can add the quarterly totals with GROUPING SETS, like this:
SELECT    COUNT (*)    AS cnt
,         CASE
              WHEN  GROUPING (TRUNC (regdate, 'MONTH')) = 0
              THEN  TO_CHAR (TRUNC (regdate, 'MONTH'), 'YYYY MON')
              ELSE  TO_CHAR (TRUNC (regdate, 'Q'),     'YYYY "Q"Q')
          END          AS label
FROM      t_cust_reg
GROUP BY  GROUPING SETS ( (TRUNC (regdate, 'MONTH'))
                        , (TRUNC (regdate, 'Q'))
Instead of calling TRUNC over and over, you might want to do it just 2 times, in a sub-query, giving aliases to the results, and then use the aliases over and over in the main query.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the exact results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002

Similar Messages

  • How to write REF-CURSOR Query in Oracle Reports

    Hello Guys!!
    I have a form in which you can select regions/divisions/locations etc by the use of check boxes. And the selected values will be inserted into a table, and based on the selected values of the table the report is run.
    The issue I have is with the query inside the Oracle reports(attached to this file).
    The query works fine until the last two EXISTS conditions.
    IF a region exists In the table report_param then it works fine but if there are no divisions in it , then the query returns no values, which is not correct.
    Someone has advised me to use a ref-cursor query inside reports tool, which I am not aware off. So, anykind of suggestions or advises are welcome. Please let me know about it as it is very urgent issue for me. Anykind of help would be greatly
    appreciated.
    Thanks,
    Vishal
    -------------------------------------------------------Query in Oracle Reports---------------------------------------------------------
    select c.key_segment, p.supplier_id,
    decode(:in_col_nm, 'BRAND',nvl(p.product_brand,'<Unknown Brand>'), 'PLN',nvl(p.product_legal_name,'<Unknown Legal Name>')) COL_NM,
    sum(a.ext_price) sales_dols,
    sum(comp_allow_pkg.get_comp_allow_stddiv(a.control_loc_id, a.product_id, a.sold_to_customer_id,
    a.doc_dt, a.ext_price, a.units)) cust_reb_dols,
    sum(a.units) units,
    sum(a.ext_cost) cost_dols
    from sales a, key_segment_plns c, product p, rep_wrtr_dw_cust h
    where a.doc_dt between :in_start_dt and :in_end_dt
    and a.customer_oc = h.control_loc_id
    and a.sold_to_customer_id = h.sold_to_cust_id
    and a.ship_to_customer_id = h.ship_to_cust_id
    and ((:in_dg_cd = 'B' and h.dealer_grower_cd in ('D','G')) or h.dealer_grower_cd = :in_dg_cd)
    and a.product_id = p.product_id
    and p.product_gl_class_cd = 'CHEM'
    and p.product_legal_name = c.product_legal_name
    and c.key_segment in ('GLYPHOSATE','PLANT HEALTH/RUST FUNGICIDES','PYRETHROIDS','STROBI FUNGICIDES')--&IN_KEY_SEGMENTS
    -- and (:in_oc = 'ALL' or (a.control_loc_id in (select control_loc from control_loc_comb_ocs where control_loc_comb = :in_oc)))
    -- SALES DATA FILTERS TO MATCH ACCUM_SALES_DG_MV
    and a.sale_type_cd in ('02','08')
    and a.document_type_cd in ('I','C','D')
    and (substr(a.product_id,-1) in ('0','1') OR nvl(upper(trim(p.product_brand)),'X') = 'TECH FEE')
    and a.units <> 0
    and a.unit_cost <> 0
    and a.unit_price <> 0
    -- NEW FILTERS ADDED 9/11/07: LOCATION(BRANCH), BUSINESS TYPE, RSM/ASM/REP
    and ((:in_loc = 'ALL') or (nvl(a.warehouse_id,'<blank>') in (SELECT param_value
    FROM report_param
    WHERE report_id = :IN_REPORT_ID
    AND session_id= :IN_SESSION_ID
    AND USER_ID = :IN_USER_ID
    AND param_name='LOCATION_TYPE')))
    and ((:in_uhs_ag = 'ALL') or (:in_uhs_ag = 'NA' and p.product_uhs_ag != 'A') or (p.product_uhs_ag = :in_uhs_ag))
    and ((:in_sales_rep = 'ALL') or (nvl(a.territory_id,'<blank>') in (SELECT param_value
    FROM report_param
    WHERE report_id = :IN_REPORT_ID
    AND session_id= :IN_SESSION_ID
    AND USER_ID = :IN_USER_ID
    AND param_name='SALES_REP_TYPE')))
    and EXISTS
    (SELECT '1'
    FROM locations l, report_param rp
    WHERE rp.report_id = :IN_REPORT_ID
    AND rp.session_id= :IN_SESSION_ID
    AND rp.user_id = :IN_USER_ID
    AND rp.param_value = l.region
    AND rp.param_name = 'REGION_TYPE'
    AND a.warehouse_id = L.ARS_LOCATION)
    and EXISTS
    (SELECT '1'
    FROM locations l, report_param rp
    WHERE rp.report_id = :IN_REPORT_ID
    AND rp.session_id= :IN_SESSION_ID
    AND rp.user_id = :IN_USER_ID
    AND rp.param_value = l.region
    AND rp.param_name = 'DIVISION_TYPE'
    AND a.warehouse_id = L.ARS_LOCATION)
    group by c.key_segment, P.supplier_id,
    decode(:in_col_nm, 'BRAND',nvl(p.product_brand,'<Unknown Brand>'), 'PLN',nvl(p.product_legal_name,'<Unknown Legal Name>'))

    Hi,
    I need your help to create a report using Ref-Cursor. please see the below thread
    Report using ref cursor or dynamic Sql

  • How to write this sql  query to oracle

    Hi sir,
    i am using one query in my sql stored procedure that is:
    select @maxtime=CONVERT(Time,Out_Time+DATEADD(n,60,0)) from shift where Shift_Code = @ShiftCode
    so here i am getting this value 01/01/1900 12:00 AM
    the same i used in oracle my query is :
    to_char(Out_Time,'1900-01-01' + 0/(24*60),'DD/MM/YYYY HH:MI AM')
    INTO v_maxtime
    FROM shift
    WHERE Shift_Code = v_ShiftCode;
    but getting error that is: Encountered the symbol INTO when expecting one of the following :=(%;
    am i doing any thing wrong.
    thanks

    APC wrote:
    The error you're getting is a syntax error. In this case because you've mangled the TO_CHAR syntax. Alas I cannot give you the correct version because I cannot unpick what you're trying to do with that statement.
    It would be easier if you expalined what business logic you're trying to implement instead of asking us to interpret a piece of shonky SQL.It's yet another of the OP's questions about how to do DATEs in Oracle (so many threads it can get very confusing - even though the OP has been asked to stick to one thread!).
    The code looks like it's based on the answer I gave here:
    How to get exact query of sql in oracle?
    but clearly he doesn't understand the basic syntax of Oracle or the datatypes he's using. Sometimes you just have to give up... (I know I have)

  • How to write the given query using 'ANY ' operator

    Hi,
    How to write the given query using 'ANY ' operator , I dont need to fetch to grade_master table twice in database, just need to fetch within the result set.
    SELECT dsg_code,dsg_name,dsg_grade FROM designation_master WHERE dsg_orgn='&&Orgn' and dsg_ctry='&&ctry'
    And dsg_loc ='&&loc' And dsg_oru = '&&oru' and dsg_grade in decode('&&radio_group',
    1, SELECT grd_code FROM grade_master WHERE grd_osm_code in (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&Orgn' and grd_ctry='&&ctry' And grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code ='&&emp_grade'),
    2, SELECT grd_code FROM grade_master WHERE grd_osm_code > (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&orgn' and grd_ctry='&&ctry' and grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code),
    3, SELECT grd_code FROM grade_master WHERE grd_osm_code < (Select grd_osm_code FROM grade_master WHERE grd_orgn='&&orgn' and grd_ctry='&&ctry' And grd_loc ='&&loc' And grd_oru = '&&oru' and grd_code ='&&emp_grade'))
    thanks
    rincy

    Hi,
    One thing I understood my your issue is you want to perform, execution of query once or fetch the results sets my minimizing the number of times executions of queries. It would be hard for us to check in this way, atleast provide some temporary data and some business rules. Only I can IN, >, < (queries logical conditons on inner query)
    - Pavan Kumar N
    - ORACLE OCP - 9i/10g
    https://www.oracleinternals.blogspot.com

  • How to write a SQL query in SAP B1 2007 B with input parameters?

    How to write a SQL query in SAP B1 2007 B with input parameters, on execution of which will ask for some input value from the user and the values will be selected from a list such as item list?

    The syntax like
    SELECT * FROM OITM T0 WHERE T0.ItemCode = '[%0\]'
    Thanks,
    Gordon

  • How to write jsp select record from Oracle  divide per page , about 50 reco

    Dear Expert,
    How to write jsp select record from Oracle divide per page , about 50 record per page.
    Thank you very much.

    I wish I could, but there is no single sign on module available for Fusion, also, so called Fusion is yet another Word With Big Letters, behind it there is yet another OC4J ( now Oracle switched to Weblogic though) container with bunsh of Oracle apps residing in it.
    Generally speaking, neither Fusion nor Oracle Apps user database does not have any single authentication module available out of the box to integrate user database.
    It's a long sad story running straight from Oracle Apps 11.0.5.
    That's why I've created JAAS single sign on login module and used it ever since at OC4J 10.2 and onwards at OC4J 10.3
    Back to the topic: to develop Apps and test them externally using the session bean I've isted above, one need to copy certain libraries from Oracle Apps server, then add them as libraries for JDeveloper project.
    Here is the complete list:
    oracle.apps.fnd.cache
    oracle.apps.fnd.cache
    oracle.apps.fnd.common
    oracle.apps.fnd.functionSecurity
    oracle.apps.fnd.metadata
    oracle.apps.fnd.security
    oracle.apps.fnd.util
    oracle.apps.jtf.cache
    oracle.apps.jtf.security
    Edited by: Faceless on Nov 26, 2009 3:04 AM

  • How to change timeout parameter value in Oracle 10g R2

    Anyone knows how to change timeout parameter value in Oracle 10g Database R2?

    Waheed Azhar wrote:
    actually i am getting ORA-01013 exception which directly relates to the timeout value but i think it's hidden parameter...What makes you think it's a hidden parameter?
    A search of MetaLink for that error turns up a number of hits, most of which a very situational specific. Exactly what are you doing when you get this error? Are you connecting over an ODBC connection? Are you getting it on a connection request? At db shutdown? During a long-running query?

  • How we create new data base in oracle 10g express edition

    hello every body.. i student of B tech n new user of oracle so please help me how we creat new data base in oracle 10g express edition

    Hello, Oracle XE can not create more than one instance, the other editions yes, but like other editions XE allows you to create database schemas, schemas logically grouped objects like tables, views, indexes created by a user. By creating an Oracle user is associated with a schema of the same name.
    Using SYS or system accounts for creating user accounts.
    Syntax to create a user:
    create user Your_user
    IDENTIFIED BY password
    default tablespace users;
    grant connect, resources to your_user;
    Edited by: rober584812 on Jun 25, 2010 9:03 PM

  • How do we find instance name in ORACLE 10g

    Hi All,
    How do we find SID name in Oracle 10g
    Thanks in advance
    Pandiarajan

    Apology accepted.
    But yes, of course I was harsh (not at you, actually, but at the plonker who thinks he can tell me that 'echo $something' is "not right").
    Do you know how many questions could be answered here if people weren't forever debating perfectly acceptable answers? If people actually stopped to read what had been written before deciding to add their tuppence-worth? If people stopped to think, "well, that's not how I would answer it... but it's good enough".
    I see so many threads here where 58 people dive in to a thread to say, 'Me too'. Another 42 will dive in to say, 'that's not right' when actually it is. And another 137 or so will usually chime in to say nothing very much except to demonstrate that they didn't understand something that was explained a lot earlier on quite clearly. Threads go on and on, when actually all that was sought originally was a simple answer to a technical issue. God knows why it happens.
    I have no problem at all being asked for clarification. I have no problem at all being corrected and having someone point out that actually that parameter doesn't exist, you made a typo, that's not the command to achieve X. When I am technically wrong, I would expect nothing less. But where so much of my time gets wasted is demonstrated in this thread perfectly. I answered the question in one post. It might not have been a perfect answer. There are many different ways of coming up with the answer on Windows, for example, and yet I didn't mention the registry at all or the Control Panel/System applet for checking environment variables once. And yet, despite all of that, in answer 1 there was sufficient information to make the OP happy. But no, that's not enough to shut some people up (and I am again not referring to you at this point).
    I don't know what it is. Some sense of, maybe, in a democracy my opinion is as good as yours even if it's entirely unnecessary, potentially confusing and adds absolutely nothing to the outcome? A desire on the part of some people to boost their post numbers?
    Too right I'm harsh. I am results-driven. I am here because I want to help others. Not because I think my opinions deserve a hearing even though the answer was posted ages ago. When I see something that looks like the opposite of that -grandstanding, look how clever I am, my opinion counts too- yeah, it annoys me somewhat. And largely because I usually end up having to untangle the confusion caused by unnecessary "contributions" from others.

  • How to access Data Guard option in Oracle 10g OEM

    Hi All,
    I have Oracle 10g ENTERPRISE EDITION on Unix envoirement. I want to setup logical standby Database through Data Guard technology. But when I brows through OEM I do not find Link for DATA GUARD????
    1) How to access Data Guard option from oracle 10g OEM.
    2) Does It come with Enterprise Edition OR I have to install it separately.
    Regards,
    Darshan

    I am managing almost everything through EM Grid Control. It is easy to setup and configure.
    Anyways, if you have read the documentation on
    Oracle® Data Guard Concepts and Administration and setup your environment accordingly then you should not have any problems. Atleast I can assure you that your production database will not be affected by it.
    Just make sure that you follow each step and read thoroughly. If you have spare machines then you can test and record your configuration before performing it on your production db. This link will provide you with the information on DataGuard.
    http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14239/concepts.htm
    If you think that way then you will never be able to do any new stuff since you will always fear that something might go wrong. Go ahead pal, try it on test machines and you will know that it is not that difficult.
    There are real experts who help people like us in this forum and I know that they are doing a pretty good job.
    All the best.
    Rgds
    Adnan

  • How to change redo log size in oracle 10g

    Hi Experts,
    Can anybody confirm how to change redo log size in oracle 10g?
    Amit

    Dear Amit,
    You can enlarge the size of existing Online Redo log files, by adding new groups with different size of files (origlog$/mirrlog$) and then carefully droping the old groups with  their associated inactive files.
    Please refer SAP Note 309526 - Enlarging redo log files to perform the activity.
    Steps to perform:
    STEP-1. Analyze the exisiting situation and prepare an action plan.
    A. You have to ensure that no more than one log switch per minute occurs during peak times.
    It may also be necessary to increase the size of the online redo logs until they are large enough.
    Too many log switches lead to too many checkpoints, which in turn lead to a high writing load in the I/O subsystem.
    Use ST04 -> Additional Functions --> Display GV$-Views
    There you can select
    Gv$LOG_HISTORY --->for determing your existing LOG switching frequency.
    GV$LOG -
    > list the status(INACTIVE/CURRENT/ACTIVE) /size/sequence no. of existing online redolog files
    GV$LOGFILE  --- > list the information of existing online  redolog files with their storage paths
    You can document the existing situation of Online Redo Log Fiile management before going to enlarge Redo Log Files.
    It will be helpful, if something goes wrong while performing activities.
    B. Based on above Situation analysis, Plan your New Redo Log Group and there Members with new optimal size.
    e.g.
    Group No.         Redo Log File Locations  u201C/oracle/<SID>/u201D                  Size
                                 /origlogA                  /mirrlogA            
    15                        log_g15m1.dbf         log_g15m2.dbf               100 MB
    17                        log_g17m1.dbf            log_g17m2.dbf               100 MB
                                /origlogB                    /mirrlogB
    16                       log_g16m1.dbf          log_g16m2.dbf            100 MB
    18                       log_g18m1.dbf            log_g18m2.dbf            100 MB
    Continue to next.....

  • How much concurrent conection is allowed in oracle 10g XE?

    How much concurrent conection is allowed in oracle 10g XE?

    Hi,
    >>How much concurrent conection is allowed in oracle 10g XE? I think that the default value on Oracle XE for the SESSIONS parameter is 40.
    Then, if you will need more concurrent sessions accessing the database, you need increase this value using alter system command for this parameter.
    Cheers

  • How to write a sql query to retrieve data entered in the past 2 weeks

    Hi,
    I have file names and last accessed date(java.sql.Date format) stored in my database table, I would like to know how I can write a query to get the name of files accessed in the past 2 weeks,I use open sql server at the back end.
    Thanks in advance.

    This has essentially nothing to do with JDBC. JDBC is just an API to execute the SQL language using Java and thus interact with the databases.
    Your problem is related to the SQL language, you don't know how to write the SQL language. I suggest you to go through a SQL tutorial (there is one at w3schools.com) and to read the SQL documentation which come along with the database in question. A decent database manfacturer has a website and probably also a discussion forum / mailinglist as well.
    I'll give you a hint: you can just use equality operators in SQL like everywhere. For example: "WHERE date < somedate".

  • How to write a Timestamp in an Oracle table?

    Hi,
    I am pretty new to SAP IdM and therefore have a very basic question.
    I am using SAP IdM 7.2 SP8 on Oracle.
    I was creating a job where I calculated some values from the database with a 'From Database' path.
    Then I wanted to store these values in a temporary table together with the timestamp when these were stored/calculated.
    Doing this in the Destination-Tab of the 'From Database'-path I got following error message...
    java.sql.SQLException: Missing IN or OUT parameter at index::2
    I did several tests and created a little test which recreates the problem...
    1. Create a Job with a 'From Database'-path
    2. In the source statement, insert...
    select
      'Test' AS Message,
      systimestamp AS TempDate
    from dual;
    3. In the destination tab add a temp Table and two columns. Since I want to add a date/timestamp-value I create a column of type 'DATE' here.
    4. After running the Job the error appears. (Here in german)
    Doing some additional tests I am able to add the date as a varchar2 if I convert the TempDate using a to_char()-function.
    Thus it seems like I misusing the Timestamp/Date data type.
    Do you have recommendations how I can add the Timestamp as a Date/Timestamp value to my table?
    Kind Regards, Andreas

    Hi,
    I really never got this to work properly and most of what follows is just my own rant caused by the annoyance of not getting this seemingly simple thing to work and are strictly my own theories not based on facts or actual knowledge of how Oracle or JDBC works, nor representing my employer in any way. Anyhow :-)
    Its possible that cause of the problem is that the timestamp is "destroyed" by NLS/JDBC when transferred from the database to the client. This is also one of the issues that varies a bit from version to version of the jdbc driver. Also the DATE datatype does not include fractional seconds, so you need to create the column as TIMESTAMP if you want that.
    The real fun thing with Oracle (or their jdbc driver) is that you can read a timestamp in the source and jdbc/NLS will convert it according to your locality setting, but you can't write what you read from Oracle back to Oracle.
    Just the same way you can use to_char to get a timestamp in a nice enough format, but when writing it to_date may not be able to parse the date back when using the exact same conversion mask...
    Example:
         select TO_CHAR(current_timestamp,'YYYYMMDD HH24:MI:SS.FFTZHTZM') from dual;
    Gives: 20140314 12:41:03.320000+0100. But both
         select TO_DATE('20140314 12:41:03.320000+0100','YYYYMMDD HH24:MI:SS.FFTZHTZM') from dual;
    and
         select TO_TIMESTAMP('20140314 12:41:03.320000+0100','YYYYMMDD HH24:MI:SS.FFTZHTZM') from dual;
    give errors.
    Rather than argue and fight with it I usually just end up using a To Database pass, check SQL Updating and write the Create Table and update/insert statements myself. Alternativly you can create the table with a trigger that automatically adds the timestamp on inserts/updates.
    1st To Database pass has no source, creates the temp table:
    The next pass has the source to read the data and insert it into the temp table:
    Then just use the current_timestamp function in the insert statement to keep it local and unconverted in the database engine...
    Br
    Chris
    Message was edited by: Per Krabsetsve

  • How to write this sql query in php code ?

    for example:
    insert into temp
    select *
    from testtable;
    after this, i will query data from sql below:
    select *
    from temp;
    how to write this php code ?
    who can help me ?
    thanks!

    Have a look at the manual to find out how to issue queries.
    http://us3.php.net/oci8

Maybe you are looking for

  • How can I exit from full-screen View?

    On the View menu, I clicked "Full screen View", but then I couldn't find any way back to normal view. I had to Force-Quit Firefox to escape. How do you exit from Full Screen View? (I tried Esc, Ctrl-C, and many other key combinations) Thanks, PeterR

  • DNG 4.2 and Canon G9 raw CR2 problem

    I have been unsuccesful getting the 4.2 DNG to convert the CR2 Canon G9 files, getting an error message that the file type is not supported. Running Windows XP Home. Any ideas as to how I can fix this. Thanks, Jeff

  • Unwanted image conversion happens in .pdf

    Hi, when I convert a word .docx to a .pdf file, the image I inserted in Word duplicates multiple times within the same .jpg area.  How do I prevent this happening to my image?  I greatly appreciate any assistance! Rita

  • Unable to handle event --Select-Options as Dropdown filled with Value Set

    Hi all, I seem to be having no luck with this problem. I have searched enough, and not come across any relevant documentation either. I am using a select options field made as a dropdown and am populating the dropdown values using the Value Set where

  • Invoking external AS from Main.asc?

    Hi all, I'm hoping anyone can point me in some intelligent direction. I have a main.asc in my FMS3.5 application. I'd like to be able to import things like AS3Crypto, com.adobe.serialization, etc, to be used in main.asc. However, there seems to be no