Help redoing a query resulting in many unions

Trying to do a query that basically shows a when a customer was visited in a certain period.
I have done this as follows:
SELECT custname,
  sysdate dateperiodfor,
  MAX(datevisited)datevisited
FROM visited,customer
WHERE custid          =visitedcustid
AND datevisited        < sysdate
GROUP BY custname, sysdate
UNION
SELECT custname,
  add_months(sysdate,-1)dateperiodfor,
  MAX(datevisited)datevisited
FROM visited,customer
WHERE custid          =visitedcustid
AND datevisited        < sysdate
GROUP BY custname,  add_months(sysdate,-1)Which works fine apart from however many months i want the dateperiodfor to go back i need to add another union and change the ADD_MONTHS(sysdate) -1 to -2, -3 etc.
Is there a better way i can structure so I can go back a set number of months i.e. 12 or 18 without the need for 12 or 18 unions?
Its going to be a VIEW though so may need to be hard coded number?

Dynamic SQL is probably not needed in this scenario. However, when you have questions like this it's always helpful to
1. Oracle version (SELECT * FROM V$VERSION)
2. Sample data in the form of CREATE / INSERT statements.
3. Expected output
4. Explanation of expected output (A.K.A. "business logic")
5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
Also see the third post in this thread:
{thread:id=2174552}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Need help on retrieving query result - NPE

    Hi, I could get results with the native query in my TOAD, but I can't get it working in my session EJB. I tried both native query and EJB ql. The query created fine, as soon as I try to retrieve results, it gets stuck.
    My native query looks like this:
    Query query = em.createNativeQuery("select sum(o.amount_reimbursed) from t_expenses o where o.employee_id = '999999911' " +
    "and o.EXPENSE_ID in (select p.expense_id from T_Per_Diem_Xref p where p.expense_Type_Xref_Id=22 " +
    "and p.expense_Id in (select e.expense_Id from T_Expenses e where e.employee_Id='999999911' " +
    "and e.expense_date > to_date('01/01/2011', 'mm/dd/yyyy') and e.expense_date < to_date('12/31/2011', 'mm/dd/yyyy')))") ;
    My EJB query looks like this:
    Query query = em.createQuery("select sum(o.amountReimbursed) from TExpenses o where o.employeeId = ?1 " +
    "and o.expenseId in (select p.expenseId from TPerDiemXref p where p.expenseTypeXrefId=?2 " +
    "and p.expenseId in (select e.expenseId from TExpenses e where e.employeeId=?1 and e.expenseDate>=?3 and e.expenseDate<=?4))");
    query.setParameter(1, employeeId);
    query.setParameter(2, expenseType);
    query.setParameter(3, fDay, TemporalType.TIMESTAMP);
    query.setParameter(4, lDay, TemporalType.TIMESTAMP);
    Either one, I get NPE at the line retrieve result.
    // sumAmt = (Double)query.getSingleResult();
    List list = query.getResultList();
    if (list != null) {
    long longAmt = (Long)list.get(0);
    sumAmt = (Double)list.get(0);
    As you can see, I tried to getSingleResult, or getResultList. also tried to convert the result to Double or Long. None worked.
    Please help and thank you for your time.
    Sophia

    Frank, thank you for your reply. I have this code in my session Facade EJB, and I get the NPE in my backing bean which calls this method. When I debug the code, it appears what really cuases the problem is in this code on the line I try to assign the query result to my variable 'sumAmt = (Double)query.getSingleResult();'. In the debug, when it reaches this line, it starts to give me all kinds of pop-up windows saying couldn't find this file or that file or packages. If I get a stack trace later, I will post it. Right now I am trying to fix something else.
    Thanks, Sophia

  • Please help me in Query result.

    Hello Friends..
    Need some help .
    I have refreshed one workbook for one sales document , and it is showing me all the data.
    Could you please tell me how can i check all the key figure value , because in Query properties it is restricted to 0.
    Means , if all the Key figure value are 0 , then it will not show that Row in Report .
    I want to see the result of 0 value as well with out changing Query properties.
    Please help me and advice me , how can i do this.
    Regards

    Hi Jain,
    Without changing the query properties it will not be possible to view all values.
    If you want to view with changing the properties of query.
    Youcan do the following steps
    select each attributes right click >restrict->bring back the restricted value->and execute the query.
    all the rows will be dispalyed
    Hope this helps
    Cheers
    Sunil

  • Help with MDX Query Result weirdness

    Hi,
    Feels like I'm posting a question every other day, hope I don't wear out my welcome.
    So I have a working query :
    with
    MEMBER Measures.[EmailCount] as IIF(ISEMPTY([Measures].[Tran Count]), 0 ,[Measures].[Tran Count])
    MEMBER Measures.AdvGroupTotal as
    SUM (EXISTING ([Dim IFA Details].[Parent Key].[Adviser Group] ,
    [Dim Date].[Fiscal].[Fiscal Year].&[FY 13/14]) , Measures.[Amount])
    MEMBER [Measures].[Income Range] as
    CASE
    WHEN Measures.AdvGroupTotal <= 10000 THEN '0-10000'
    WHEN Measures.AdvGroupTotal <= 50000 THEN '10001-50000'
    WHEN Measures.AdvGroupTotal <= 100000 THEN '50001-100000'
    WHEN Measures.AdvGroupTotal <= 200000 THEN '100001-200000'
    else '200000-'
    end
    SELECT { [Measures].[Amount] , Measures.[EmailCount], Measures.AdvGroupTotal, measures.[income range]}
    ON COLUMNS,
    [Dim IFA Details].[Parent Key].[Adviser Group].Members * [Dim Date].[Fiscal Quarter].children
    having Measures.AdvGroupTotal > 100
    on rows
    FROM [Income and Emails Cube]
    where
    ([Dim Date].[Fiscal].[Fiscal Year].&[FY 13/14]
    Great, gives me back what I expect
    So now I'm thinking, actually let's lose the Adviser Groups and just have it by Fiscal Quarter and Income Range, dropping that I lose my income range and get this:
    I figured its related to Income Range being a measure, so I tried making income range a calculated member of a dimension
    with
    MEMBER Measures.[EmailCount] as IIF(ISEMPTY([Measures].[Tran Count]), 0 ,[Measures].[Tran Count])
    MEMBER Measures.AdvGroupTotal as
    SUM (EXISTING ([Dim IFA Details].[Parent Key].[Adviser Group] ,
    [Dim Date].[Fiscal].[Fiscal Year].&[FY 13/14]) , Measures.[Amount])
    MEMBER [Dim IFA Details].[Parent Key].[Income Range] as
    CASE
    WHEN Measures.AdvGroupTotal <= 10000 THEN '0-10000'
    WHEN Measures.AdvGroupTotal <= 50000 THEN '10001-50000'
    WHEN Measures.AdvGroupTotal <= 100000 THEN '50001-100000'
    WHEN Measures.AdvGroupTotal <= 200000 THEN '100001-200000'
    else '200000-'
    end
    SELECT { [Measures].[Amount] , Measures.[EmailCount], Measures.AdvGroupTotal}
    ON COLUMNS,
    ( [Dim Date].[Fiscal Quarter].children, [Dim IFA Details].[Parent Key].[Income Range] )
    on rows
    FROM [Income and Emails Cube]
    where
    ([Dim Date].[Fiscal].[Fiscal Year].&[FY 13/14]
    This then came back with some unexpected results:
    The amount and email count are now the Income Range and still didnt get the income grouping I want.
    What am I doing wrong?
    Thanks for reading.
    Regards
    Jon

    Hi JLJ1976,
    According to your description, you have some issue when changing the measure into a dimension member. Right?
    In this scenario, the reason why you get the incorrect result set is you make a measure into dimension member. In your query, the Income Range is based on the Measure AdvGroup Total, and the AdvGroup Total value depends on how your dimension slice the cube.
    If you slice the cube on date members, you will get a much smaller AdvGroup Total value. So the Measure XXX return dynamic values because it always based on dimension slicer. For dimension members, they should be static values appear on axis to slice the cube
    data on a data. So you should make the Income Range into a calculated measure because it's based on a Quarter sliced Measure. Otherwise, it will return null value (in your query, it's the else part result) because you are measuring a measure.
    For more explanation about dimensions and Measures, please refer to links below:
    Measures and Measure Groups
    Introduction to Dimensions (Analysis Services - Multidimensional Data)
    Best Regards,
    Simon Hou
    TechNet Community Support

  • Scroll to bottom of query results

    SQL Developer 1.2
    DB 9.2.0.7
    Is there any way to quickly get to the bottom of the query results? I'm transitioning off from SQL Navigator and use this feature all the time. Most query results are many many screens long so this is a very useful feature.

    Although encouraged to filter and/or order your result set to conserve I/O and memory, you can always scroll to bottom with ctrl-end or ctrl-pgdown.
    Regards,
    K.

  • Unable to create report. Query produced too many results

    Hi All,
    Does someone knows how to avoid the message "Unable to create report. Query produced too many results" in Grid Report Type in PerformancePoint 2010. When the mdx query returns large amount of data, this message appears. Is there a way to get all
    the large amount in the grid anyway?
    I have set the data Source query time-out under Central Administration - Manager Service applications - PerformancePoint Service Application - PerformancePoint Service Application Settings at 3600 seconds.
    Here Event Viewer log error at the server:
    1. An exception occurred while running a report.  The following details may help you to diagnose the problem:
    Error Message: Unable to create report. Query produced too many results.
            <br>
            <br>
            Contact the administrator for more details.
    Dashboard Name:
    Dashboard Item name:
    Report Location: {3592a959-7c50-0d1d-9185-361d2bd5428b}
    Request Duration: 6,220.93 ms
    User: INTRANET\spsdshadmin
    Parameters:
    Exception Message: Unable to create report. Query produced too many results.
    Inner Exception Message:
    Stack Trace:    at Microsoft.PerformancePoint.Scorecards.Server.PmServer.ExecuteAnalyticReportWithParameters(RepositoryLocation analyticReportViewLocation, BIDataContainer biDataContainer)
       at Microsoft.PerformancePoint.Analytics.ServerRendering.OLAPBase.OlapViewBaseControl.ExtractReportViewData()
       at Microsoft.PerformancePoint.Analytics.ServerRendering.OLAPBase.OlapViewBaseControl.CreateRenderedView(StringBuilder sd)
       at Microsoft.PerformancePoint.Scorecards.ServerRendering.NavigableControl.RenderControl(HtmlTextWriter writer)
    PerformancePoint Services error code 20604.
    2. Unable to create report. Query produced too many results.
    Microsoft.PerformancePoint.Scorecards.BpmException: Unable to create report. Query produced too many results.
       at Microsoft.PerformancePoint.Scorecards.Server.Analytics.AnalyticQueryManager.ExecuteReport(AnalyticReportState reportState, DataSource dataSource)
       at Microsoft.PerformancePoint.Scorecards.Server.PmServer.ExecuteAnalyticReportBase(RepositoryLocation analyticReportViewLocation, BIDataContainer biDataContainer, String formattingDimensionName)
       at Microsoft.PerformancePoint.Scorecards.Server.PmServer.ExecuteAnalyticReportWithParameters(RepositoryLocation analyticReportViewLocation, BIDataContainer biDataContainer)
    PerformancePoint Services error code 20605.
    Thanks in advance for your help.

    Hello,
    I would like you to try the following to adjust your readerquotas.
    Change the values of the parameters listed below to a larger value. We recommend that you double the value and then run the query to check whether the issue is resolved. To do this, follow these steps:
    On the SharePoint 2010 server, open the Web.config file. The file is located in the following folder:
    \Program Files\Microsoft Office Servers\14.0\Web Services\PpsMonitoringServer\
    Locate and change the the below values from 8192 to 16384.
    Open the Client.config file. The file is located in the following folder:
    \Program Files\Microsoft Office Servers\14.0\WebClients\PpsMonitoringServer\
    Locate and change the below values from 8192 to 16384.
    After you have made the changes, restart Internet Information Services (IIS) on the SharePoint 2010 server.
    <readerQuotas
    maxStringContentLength="2147483647"
    maxNameTableCharCount="2147483647"
    maxBytesPerRead="2147483647"
    maxArrayLength="2147483647"
                  maxDepth="2147483647"
    />
    Thanks
    Heidi Tr - MSFT
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • Select query resulting in redo?

    Hi All,
    Does select query results in redo? In what cases this happens?
    Regards,
    Sphinx

    mtefft wrote:
    Another possibility is that the SELECT query invokes a PL/SQL function that performs insert, update or delete.
    This is a poor practice for a number of reasons but they are out there.
    Disagree with that. Proof:
    SQL> create table x(y number);                                   
    Table created.                                                   
    SQL> create function f return number as                          
      2  begin                                                       
      3  insert into x values (2);                                   
      4  return 1;                                                   
      5  end;                                                        
      6  /                                                           
    Function created.                                                
    SQL> select dummy, f() from dual;                                
    select dummy, f() from dual                                      
    ERROR at line 1:                                                 
    ORA-14551: cannot perform a DML operation inside a query         
    ORA-06512: at "HR.F", line 3                                     

  • Display query's result (with many rows & field) into a list ?

    I'd like to display the result of a query wich returs many rows without using a list of values but another component which allowed the display of sereval columns at the same time.
    Note: I can't use a LOV because I don't want to return no value, and I need a TLIST presentation.
    null

    A kludgy solution would be to create a database view that combines the multiple columns into a single standardly formatted column, and use that for displaying in a jcombobox.
    Depends upon whether you like to code Java or like to play in the database. grin
    If you do that Java solution please post the code here!

  • Query results display help

    Hello
    I'm having a issue with displaying the results of my query output.
    When I cfloop over the results.. the part number is being output on 3 different rows... when I want it on one row querying multiple tables.. and you cant use the group option with the cfloop
    here is the query
    <cfquery datasource="wire" name="testss3">
       SELECT a.part AS pparts, a.wireid AS wireidA, a.strnds, a.wt, a.sps1, a.sps2, a.sps3, a.tin, b.slookup AS lid, b.wireid AS wireidB, b.reelid AS reelnmbr, d.reelid AS rlid, d.rname, d.rsku, d.rcost, e.plookupid, e.prctid, e.wireid AS wireidE, f.prctid, f.percentage, g.rsize
       FROM Mpart a, slookupt b, reeltbl d, prctlup e, prct f, spoolsize g
       WHERE a.wireid = b.wireid AND e.prctid = f.prctid AND a.wireid = e.wireid AND b.reelid = d.reelid AND g.spoolSizeid = b.spoolSizeid
       </cfquery>
    <table border="1" border="1">
    <tr>
            <td></td>
            <td bgcolor="#CCCCCC" class="style23">Part No.  </td>
            <td bgcolor="#CCCCCC" class="style23">Wt./Mft.</td>
            <td bgcolor="#CCCCCC" class="style23" colspan="3">Spool Sizes (Cost/ft.)</td>
            <td> </td>
          </tr>
       <cfloop query="testss3"><cfoutput>
         <tr>
            <td></td>
               <td align="left" class="style23">#pparts# @</td>
                <td align="left" class="style23">#wt#</td>
               <td align="left" class="style23">
                #rsize# #rcost#  #wireidA#</cfoutput></cfloop></td>
            <td> </td>
           </tr>      
    </table>
    Part No. 
    Wt./Mft.
    Stock Spool Sizes (Cost/ft.)
    10 sol @
    31.43
    1000 2.8000 1 
    10 sol @
    31.43
    2500 5.9800 1 
    10 sol @
    31.43
    5000 7.3000 1 
    10T @
    31.43
    1000 2.8000 2 
    10T @
    31.43
    2500 5.9800 2 
    10T @
    31.43
    5000 7.3000 2 
    8 sol @
    50
    500 2.8000 4 
    8 sol @
    50
    1000 5.9800 4 
    8 sol @
    50
    5000 7.3000 4 
    8T @
    50
    500 2.8000 5 
    8T @
    50
    1000 5.9800 5 
    8T @
    50
    5000 7.3000 5
    the first row should read 10 sol | 31.43 | 1000 | 2500 | 5000
    the next row 10T | 31.43 | 1000 | 2500 | 5000
    Any help would be much appreciated!
    Thanks!

    Hi Dan
    When i use the cfouput with the group attribute... the query only returns one of the columns from the table for stock spool sizes...
    so the new query results will have 1 part which is good 10 Sol | 31.43 | 1000
    but only 1000 .. when it should return 1000 | 2500 | 5000  based on that wireid
    Thanks

  • Help assigning a   calculated arbitrary  ID to a query result set

    Given the sample query result..
    (sorry about the formatting of the output)
    GROUPID LAST_NAME FIRST_NAME INITIALS EMAIL PHONE count(PHONE)
    GP2001 Troy Diana s [email protected] 123-456-7890 2
    GP2001 Troy Diana s [email protected] 123-456-7890 2
    GP2006 Thomas Carl p [email protected] 789-100-1112 1
    GP2007 Riker William T [email protected] 866-908-6654 1
    GP3001 Laforge Jody m jlaforge@enterprisenet 456-789-9000 3
    GP3001 Laforge Jody m [email protected] 456-789-9000 3
    GP3001 Laforge Jody m [email protected] 456-789-9000 3
    GROUP_ID is a calculated field from a select statement.
    Individuals with one phone number (ph_cnt = 1)
    is assigned an arbitrary unique GROUP_ID.
    Individuals, appearing more than once, with more than one phone (ph_cnt > 1)
    are giving the same GROUP_ID.
    I was thinking of using a case statement in this case...but got stuck on generating the GROUP_ID based
    on the phone count.
    select case
    when ph_cnt = 1 then select 'GP'||to_char(sysdate,'hhmisssss') from dual)
    when ph_cnt > 2 then <assign a unique group_id to each set of duplicates/triplicate...etc>
    end GROUP_ID,
    last_name,
    first_name,
    initials,
    email,
    phone
    (select last_name,
    first_name,
    initials,
    email,
    phone,
    count(phone) ph_cnt
    from my tab
    group by
    last_name,first_name,initials,email,phone)
    Edited by: ch**** on Apr 25, 2011 7:20 AM

    Try this,
    SELECT 'GP' || 1000 + DENSE_RANK () OVER (ORDER BY phone ASC) groupid,
           last_name,
           first_name,
           initials,
           email,
           phone,
           COUNT (1) OVER (PARTITION BY phone) ph_cnt
      FROM my tab;G.

  • Getting query results from a PL/SQL procedure

    Hi! So, I’m a little stumped and I can’t seem to find the answer to what I believe is probably a simple question…
    So, here goes… I have a big ol’ union query that I use to create a report on a page, it’s about 25k – not over the 32k limit, but fails to be able to compile every time (I always get a 400 – Bad Request error). I’m not sure why this is happening, but I can remove a union statement and it compiles just fine – so it has something to do with the size of the query. ANYWAY – I’ve resolved that I should put this bad boy into the database as a stored procedure and just call it from Apex, my problem is I can’t figure out quite how to do this with variables, etc.…
    Instead of giving you my whole big query, I’ll use the emp table as the concept is the same:
    Say we have a query that creates a report on a page:
    select empno, ename, job, mgr, hiredate, sal, comm, deptno
    from emp
    where job = :P_JOB
    and hiredate >= :P_HIREDATE;
    How would I take this query, create it as a stored procedure on the db, pass the variables from Apex and return the query result set from the stored proc as a report?
    I really appreciate any help on this!
    Best,
    Gilcrest

    Hi Gilcrest,
    You should create the query as a View and use the view name and the WHERE clause in the report's sql source.
    Andy

  • How to display query result in seperated page.

    How to display query result in seperated page, if the results are very big (more than 5000 records) and there are so many concurrent users (about 500 - 1000 users).
    Are there any solutions or frameworks?
    Plese help me .........
    thanks,
    --bhasin

    Hi,
    How to display query result in seperated page?I think RowSet will be the better technology to use in this
    situation.For more information on this please visit http://developer.java.sun.com/developer/Books/JDBCTutorial/chapter5.html
    which explains in detail about RowSets.
    Hope this helps.
    Good Luck.
    Gayam.Srinivasa Reddy
    Developer Technical Support
    Sun Microsystems
    http://www.sun.com/developers/support/

  • Need QUERY result in Graph

    Dear Experts,
    I am having the following requirement.
              Can it be possible to present the QUERY result in Graph ?
    I read many thread in SDN, I found through APD/WAD we can do it . But I am confused.
    But I am not getting any thread , How to proceed step by step ?
    Kindly help..
    Thanks,
    Sethi

    Hi,
    If you are using Bex Query make as work book ,in that you can add charts and save as work book not as a query.
    To insert the chart
    Go to insert tab in the Excel(Work book) choose which chart  you want in that.
    After that go the chart which you have selected, right click and go to select data option, choose series for Entries and choose labels for category.
    Hope it helps.
    Thanks & Regards,
    Ramnaresh.P.

  • Exporting BEx Query results to CSV or other files.

    Hi All,
    We have a report designed in WAD, which uses a BEx query to display department’s information. Because of amount of data in the results it crashes when u get all the Free Characters into ROWS(Error is : Result set too large(552244 cells); data retrieval restricted by configuration (maximum =500000 cells).  It is a requirement from the user to have all the free characteristics in the rows( which I can understand is not the right way to go ahead). As it is crashing when you add last characteristic(WBS Purpose)  into the rows, they aren’t able to export data into spread sheet from the results. (as there are no results)
    Now my question is…..is there any way we can export the results from BEX query into any format for example text or csv? If yes, can we schedule that process? Please note that this characteristics are displayed as hierarchies.
    Am new to SAP BW and its been only six months since I have been in this role. Any help would be much appreciated???
    I looked online and some where in the forum it was mentioned of using program RSCRM_BAPI, but looks like it needs some sort of downloads from SAP.
    Is there any other way to export the BEx query results?
    Cheers
    Sandeep

    Hello Sandeep,
    You can use the Item "Context Menu" in your WAD and in the properties by default you can see the Options:
    Export to Excel & Export to CSV will be there and also there are many options which you wanted to see.
    It works for you!!!
    With Regards,
    PJ.

  • Need Help on below Query.

    Hi All,
    Need Help on below Query.
    Consider,
    "test9" Table Data in COLUMN "Name" AS
    Name
    =====
    'a'
    'b'
    'c'
    'd'
    'e'
    I am writing a query as :
    SELECT * FROM test9 WHERE Name IN ('a','b','c','d','e','f','g')
    I want result set as , It should show data as -
    'f'
    'g'
    i.e. data which does not exists in the table and which is give in in clause
    Is it possible in a single query.

    You can put the data that is to be checked for into a table instead or an inline view, for example:
    with t as
    (select 'a' as c1 from dual
    union all
    select 'b' from dual
    union all
    select 'c' from dual
    union all
    select 'd' from dual
    union all
    select 'e' from dual)
    select c1 from (select 'a' as c1 from dual
    union all
    select 'b' from dual
    union all
    select 'c' from dual
    union all
    select 'd' from dual
    union all
    select 'e' from dual
    union all
    select 'f' from dual
    union all
    select 'g' from dual)
    minus
    select c1 from t
    C
    f
    g
    2 rows selected.

Maybe you are looking for

  • Why does Illustrator keep crashing and closing?

    I'm using Windows 7 (64bit.) and have AI CS6. With no warning, AI keeps shutting down saying that my preferences are corrupt, and it's reverting to the old ones. I have absolutely no clue what's happening, except that it's been installed for less tha

  • WHERE clause that depends on variable?

    I have variable @Grade with possible values "High School Girls" or "Middle School Boys". When @Grade is "High School Girls", then my query looks like this: SELECT * FROM TABLE WHERE GRADE > 9 AND GENDER = 'FEMALE' When @Grade is "Middle School Boys",

  • Photoshop CS5 64 bit crashes at launch, save as, and when opening photos from Lightroom.

    I have had this problem intermittently for years with different versions and different computers, but this time it is not going away.  I need to use the 64 bit version for large files, but it keeps crashing in several different ways. 1- I open the pr

  • NAM Upgrade from 3.6(1b) to 4.0 or 4.2

    Dear All I followed the instruction from the Document "Cisco Branch Router Series (NME-NAM) Installation and Configuration Note, 4.2" and the URL is " http://www.cisco.com/en/US/docs/net_mgmt/network_analysis_module_software/4.2/branch_router/configu

  • UseBean tag gives error please help

    Hi, I keep getting an error in my browser regarding the java.util.Collection class I am including in my jsp page. <%@ page import="java.util.*, src.com.database.*, src.com.data.*, src.com.business.*" %> <jsp:useBean id="persons" scope="request" class