How to construct query with null parameters in jpa 2.0

Hi,
I am creating a jpa 2.0 application. I have an entity with a large number of fields
@Entity
@Table(name="notations")
public class Notation implements Serializable {
     private static final long serialVersionUID = 1L;
     @Id
     private Integer id;
     @Column(name="action_count")
     private Integer actionCount;
     @Column(name="adaptability_comment")
     private String adaptabilityComment;
     @Column(name="adaptability_score")
     private Integer adaptabilityScore;
     private String comment;
     @Column(name="compatibility_comment")
     private String compatibilityComment;
     @Column(name="compatibility_score")
     private Integer compatibilityScore;
     @Column(name="consistency_comment")
     private String consistencyComment;
     @Column(name="consistency_score")
     private Integer consistencyScore;
     @Column(name="controlpoint_name")
     private String controlpointName;
     @Column(name="device_brand")
     private String deviceBrand;
     @Column(name="device_name")
     private String deviceName;
     @Column(name="error_management_comment")
     private String errorManagementComment;
     @Column(name="error_management_score")
     private Integer errorManagementScore;
     @Column(name="explicit_control_comment")
     private String explicitControlComment;
     @Column(name="explicit_control_score")
     private Integer explicitControlScore;
     @Column(name="functionality_name")
     private String functionalityName;
     @Column(name="guidance_comment")
     private String guidanceComment;
     @Column(name="guidance_score")
     private Integer guidanceScore;
     @Column(name="is_available")
     private Boolean isAvailable;
     private String protocol;
     @Column(name="significance_comment")
     private String significanceComment;
     @Column(name="significance_score")
     private Integer significanceScore;
     @Column(name="tester_name")
     private String testerName;
     @Column(name="use_case_name")
     private String useCaseName;
     @Column(name="workload_comment")
     private String workloadComment;
     @Column(name="workload_score")
     private Integer workloadScore;
        getters, settersI am using a method to update this entity as the user changes different fields. My method takes (almost) all fields, but only one (or few) have values, the others are null.
public Notation updateNotation(Integer id, Boolean isAvailable, String protocol, String deviceBrand,
               String deviceName,String testerName, Date ratingDate, String functionalityName,
               String useCaseName,     String controlPointName, Integer actionCount, String comment,
               Integer adaptabilityScore, Integer compatibilityScore, Integer consistencyScore,
               Integer errorManagementScore, Integer explicitControlScore, Integer guidanceScore, Integer significanceScore,
               Integer workloadScore, String adaptabilityComment, String compatibilityComment,
               String consistencyComment, String errorManagementComment, String explicitControlComment,
               String guidanceComment, String significanceComment, String workloadComment) throws PersistenceException{
          String setString = "";
          if(isAvailable != null)
               setString += "n.isAvailable = '" + isAvailable + "',";
          if(!(protocol==null||protocol.isEmpty()))
               setString += "n.protocol = '" + protocol + "',";
          if(!(deviceBrand==null||deviceBrand.isEmpty()))
               setString += "n.deviceBrand = '" + deviceBrand + "',";
          if(!(deviceName==null||deviceName.isEmpty()))
               setString += "n.deviceName = '" + deviceName + "',";
          if(!(testerName==null||testerName.isEmpty()))
               setString += "n.testerName = '" + testerName + "',";
          if(!(functionalityName==null||functionalityName.isEmpty()))
               setString += "n.functionalityName = '" + functionalityName + "',";
          if(!(useCaseName==null||useCaseName.isEmpty()))
               setString += "n.useCaseName = '" + useCaseName + "',";
          if(!(controlPointName==null||controlPointName.isEmpty()))
               setString += "n.controlPointName = '" + controlPointName + "',";
          if(actionCount != null)
               setString += "n.actionCount = '" + actionCount + "',";
          if(!(comment==null||comment.isEmpty()))
               setString += "n.comment = '" + comment + "',";
          if(adaptabilityScore != null)
               setString += "n.adaptabilityScore = '" + adaptabilityScore + "',";
          if(compatibilityScore != null)
               setString += "n.compatibilityScore = '" + compatibilityScore + "',";
          if(consistencyScore != null)
               setString += "n.consistencyScore = '" + consistencyScore + "',";
          if(errorManagementScore != null)
               setString += "n.errorManagementScore = '" + errorManagementScore + "',";
          if(explicitControlScore != null)
               setString += "n.explicitControlScore = '" + explicitControlScore + "',";
          if(guidanceScore != null)
               setString += "n.guidanceScore = '" + guidanceScore + "',";
          if(significanceScore != null)
               setString += "n.significanceScore = '" + significanceScore + "',";
          if(workloadScore != null)
               setString += "n.workloadScore = '" + workloadScore + "',";
          if(!(adaptabilityComment==null||adaptabilityComment.isEmpty()))
               setString += "n.adaptabilityComment = '" + adaptabilityComment + "',";
          if(!(compatibilityComment==null||compatibilityComment.isEmpty()))
               setString += "n.compatibilityComment = '" + compatibilityComment + "',";
          if(!(consistencyComment==null||consistencyComment.isEmpty()))
               setString += "n.consistencyComment = '" + consistencyComment + "',";
          if(!(errorManagementComment==null||errorManagementComment.isEmpty()))
               setString += "n.errorManagementComment = '" + errorManagementComment + "',";
          if(!(explicitControlComment==null||explicitControlComment.isEmpty()))
               setString += "n.explicitControlComment = '" + explicitControlComment + "',";
          if(!(guidanceComment==null||guidanceComment.isEmpty()))
               setString += "n.guidanceComment = '" + guidanceComment + "',";
          if(!(significanceComment==null||significanceComment.isEmpty()))
               setString += "n.significanceComment = '" + significanceComment + "',";
          if(!(workloadComment==null||workloadComment.isEmpty()))
               setString += "n.workloadComment = '" + workloadComment + "',";
          if(setString!="") setString = setString.substring(0, setString.length()-1);
          String queryString = "UPDATE Notation n SET " + setString + " WHERE n.id = ?1";
          Query q = em.createQuery(queryString);
          q.setParameter(1, id);
          q.executeUpdate();
          return (Notation) em.createQuery("SELECT n FROM Notation n WHERE n.id = ?1").setParameter(1, id).getResultList().get(0);
     }So my question I think is somewhat obvious. What is a good way to construct my query, so that I am not forced to have such an ugly and laborious code (again, knowing that most of the arguments are null)?
Thanks in advance
Edited by: StefanC on Jan 27, 2010 3:01 AM

That is a good point, I will do the operations directly on the entity. However, that still doesn't save me from having to write all those if statements and having an ugly code.
Husain.AlKhamis wrote:
Exactly, this is the concept behind JPA --> you have to write zero SQL queries.It's true that you don't have to write any queries for update and remove, however you still have to write JPQL queries (pretty much like SQL) to selections.

Similar Messages

  • How to write XSJS Select Query with input parameters

    Hello Experts,
    I am creating a xsjs file and in that file I am trying to write a Select Query based on a Calculation View
    I have tried it the following way:
    var query = 'SELECT TOP 100 \"Name\", \"Address\", \"City\", \"Country\" FROM \"_SYS_BIC\".\"Test.HL/AddressView\"'
        + 'WITH PARAMETERS(\'PLACEHOLDER\' = (\'$$P_Name$$\', \' Akhil \'),'
      + '\'PLACEHOLDER\' = (\'$$P_City$$\', \' Lucknow \'))';
    But it gives me the "Mixed spaces and tabs error".
    How should I write XSJS Select Query with input parameters?
    Regards,
    Rohit

    >But it gives me the "Mixed spaces and tabs error".
    Mixed spaces and tabs has nothing to do with the syntax of the statement. You used both spaces and the tab in the content - which JSLint doesn't like.  Remove the beginning spaces of each line and use only one or the other.
    The actual syntax of your statement doesn't look right.  The problem is that you are escaping the \ when you don't need to if you are using ' instead of " for your string.  You escape with \" in the first line but then escape with \' in the 2nd and 3rd line.  That is going to cause serious parsing problems with the command.

  • How do I check for null parameters in  Process Validations?

    I am trying to create a Unit Test that validates that a record has been inserted into a table. However I am having problems when dealing with null parameters.
    I created a simple table and insert procedure:
    create table TEST_TAB (
    A varchar2 (30) not null,
    B varchar2 (30));
    create or replace procedure TEST_TAB_INS (P_A in varchar2, P_B in varchar2) is
    begin
    insert into TEST_TAB values (P_A, P_B);
    end;
    Then I created a Unit Test with two implementations:
    The first executes TEST_TAB_INS ('One', 'Two')
    The second executes TEST_TAB_INS ('One', null)
    I attached the following Query Returning Rows Process Validation to both implementations:
    select *
    from TEST_TAB
    where A = '{P_A}'
    and (B = '{P_B}' or '{P_B}' is null)
    This should allow for the case where P_B is null. However the second test fails with a "Query check returned no rows" error.
    I've tried altering the test to use nvl, but get the same results:
    select *
    from TEST_TAB
    where A = '{P_A}'
    and (B = '{P_B}' or nvl ('{P_B}', 'XXXX') = 'XXXX')
    However, the following test succeeds:
    select *
    from TEST_TAB
    where A = '{P_A}'
    and (B = '{P_B}' or nvl ('{P_B}', 'XXXX') = '{P_B}')
    Which suggests that null parameters are not being treated as nulls in Process Validations

    I've found a way to solve this. By changing the test to:
    select *
    from TEST_TAB
    where A = '{P_A}'
    and (B = '{P_B}' or '{P_B}' = 'NULL')
    I am able to get both to get both implementations to succeed.
    Edited by: AJMiller on Dec 28, 2012 4:24 AM

  • Running a SQL Stored Procedure from Power Query with Dynamic Parameters

    Hi,
    I want to execute a stored procedure from Power Query with dynamic parameters.
    In normal process, query will look like below in Power Query. Here the value 'Dileep' is passed as a parameter value to SP.
        Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData 'Dileep'"]
    Now I want to pass the value dynamically taking from excel sheet. I can get the required excel cell value in a variable but unable to pass it to query.
        Name_Parameter = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
        Name_Value = Name_Parameter{0}[Value],
    I have tried like below but it is not working.
    Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData Name_Value"]
    Can anyone please help me with this issue.
    Thanks
    Dileep

    Hi,
    I got it. Below is the correct syntax.
    Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData '" & Name_Value & "'"]
    Thanks
    Dileep

  • How to use Count with Date Parameters

    Hello,
    I am having issues using the Count() function in conjunction with date parameters.
    This is a Siebel report and in my report I have 2 date parameters(From Date, To Date). In a nutshell I am basically trying to count Opportunities that has a start date within the given date period. However I don't see a reasonable way to put my date parameters within the Count() function. The reason being is that I need to have a huge chunk of code to convert the dates into a common format that can be compared, and it won't even fit within the code block in my rtf template. I am not even sure how to put multiple conditional statements inside a Count() function since all the examples I have seen are very simple.
    Anyone have a suggestion on how to use Count() with date parameters?
    Thanks.

    Any chance you can get the date formats in the correct format from siebel?
    I don't know Siebel - so I can't help you with that. If you get the correct format it is just
    <?count(row[(FromDate>=date) and  (date<=ToDate))?>
    Otherwise the approach would probably need to use string function to get year/monthd/day from the date
    and store it into a varialbe and compare later the same way
    <?variable@incontext:from; ....?>
    <?variable@incontext:to; ...?>
    <?count(row[($from>=date) and  (date<=$to))?>
    Potentially you can use the date functions such as xdofx:to_date to do the conversion
    [http://download.oracle.com/docs/cd/E12844_01/doc/bip.1013/e12187/T421739T481158.htm]
    But I am not sure if they are available in your siebel implementation.
    Hope that helps

  • Extract Sql Query with Actual Parameters from Report

    Hi
    I am able to extract query from Crystal Report using the following code :
    ReportDocument.ReportClientDocument.RowSetController.GetSqlStatement(new GroupPath, out tmp);
    But the sql query retrieve comes in the following format :
    select name , trans_code, account_code from command_query.accounts
    where account_code = {?Command_query_Prompt0}  and effective_date < '{?Command_query_prompt1 }'
    The parameters which I m using in the reports are :
    Account_Code and Effective_Date .
    Why does my extracted sql translates it into {?Command_query_Prompt0} and '{?Command_query_prompt1 }' .
    Is there any way to map this to the actual parameter values ?
    OR
    Can we extract the query after assigning the values ?
    Any help is appreciated ... 
    Thanks
    Sanchet

    hi,
    You can create nested sql query with conditional parameters,
    For example
    Select Code From OITT Where Code IN (Select ItemCode From OITM
    Where ItemName LIKE '[%0]' + '%%')
    Edited by: Jeyakanthan A on Jun 9, 2009 12:31 PM

  • Performance with null parameters

    The below is the main cursor for a small report with some horrible performance. The report is taking 30 to 40 minutes to generate just a few rows of data. After checking my joins and whether the indexes were correct and all the other simple things, I began removing the lines on the bottom that are just used to insert incoming parameters. What I found is that if I comment out the two lines on the bottom of the statement (with v_person_id and v_sup_id), the query returns immediately if I pass a start and end date only and leave the other parameters as null. If I run the query with those lines in and pass null for those values also, it goes back to 30 minutes or so. I am confused as passing them as null should make the line evaluate to ppf.person_id = ppf.person_id. We use this technique with all of our reporting when we pass null values but for some reason it is failing horribly in this query. Can anyone see what I am doing wrong?
    SELECT ppf.employee_number,
            ppf.full_name,
            loc.attribute3,
            loc.location_code,
            glc.segment1,
            glc.segment2,
            glc.segment3,
            org.name,
            (SELECT ppf1.employee_number||'~'||ppf1.full_name
                 FROM per_all_people_f ppf1
                WHERE trunc(sysdate) between ppf1.effective_start_date and ppf1.effective_end_date
                  AND ppf1.person_id = asg.supervisor_id
                   AND rownum = 1) supervisor,
            past.per_system_status,
            hts.approval_status
      FROM hr.per_all_people_f ppf,
              hr.per_all_assignments_f asg,
            hr.per_assignment_status_types past,
              hr.hr_all_organization_units org,
           hr.hr_locations_all loc,
            hxc.hxc_timecard_summary hts,
            hr.per_person_type_usages_f ppu,
            gl.gl_code_combinations glc,
            hr.per_person_types ppt
    WHERE ppu.effective_end_date BETWEEN ppf.effective_start_date AND ppf.effective_end_date
       AND ppu.effective_end_date BETWEEN asg.effective_start_date AND asg.effective_end_date
       AND (   (:v_start BETWEEN ppu.effective_start_date AND ppu.effective_end_date
            OR (:v_end BETWEEN ppu.effective_start_date AND ppu.effective_end_date
            OR (ppu.effective_start_date BETWEEN :v_start AND :v_end
       AND asg.primary_flag = 'Y'
       AND asg.assignment_type = 'E'
       AND asg.assignment_status_type_id = past.assignment_status_type_id
       AND asg.organization_id = org.organization_id
       AND asg.location_id = loc.location_id
       AND asg.default_code_comb_id = glc.code_combination_id
       AND ppf.person_id = ppu.person_id
       AND ppf.person_id = asg.person_id
       AND ppu.person_type_id = ppt.person_type_id
       AND ppt.user_person_type = 'Employee'
       AND ppf.person_id = hts.resource_id
       AND hts.start_time between :v_start and :v_end
       AND org.name = NVL(:v_department, org.name)
       AND loc.location_code = NVL(:v_location, loc.location_code)
       AND glc.code_combination_id = NVL(:v_gl_code_id, glc.code_combination_id)
       AND asg.supervisor_id = NVL(:v_sup_id, asg.supervisor_id)---------------------------------------------------------------
       AND ppf.person_id = NVL(:v_person_id, ppf.person_id)-------------------------------------------------------------------

    user7726970 wrote:
    Now I am more confused as we tried something similar yesterday and it did not help but your version makes it respond immediately. Thanks for this. Would you please explain a little why your version works where my version does not?
    and decode(:v_sup_id,null,'x',asg.supervisor_id) = decode(:v_sup_id,null,'x',:v_sup_id)
    and decode(:v_person_id,null,'x',ppf.person_id)  = decode(:v_person_id,null,'x',:v_person_id)that depends on your version. the example that i have posted is simply to verify if your variable is null then use a character 'x'. that is like where 'x' = 'x' which does not use any table column or simply does nothing at all. and if the variable is not null simply use the table column with the variable and i am assuming that the table column has an index on it will utilize it for performance.

  • Content presenter: datasource based on CMIS query with URL parameters

    Hi all,
    I am trying to create a page containing a content presenter taskflow that is based on a CMIS query containing URL parameters. In my component properties I define the following query for my datasource:
    +SELECT * FROM ora:t:IDC:GlobalProfile WHERE ora:p:xqblIntranetSubGroep='${param.qblSubGroep}'+
    I have a URL parameter qblSubGroep containing the value "Nieuws".
    Somehow my page does not show any content. It looks like the parameter value is not passed to the data source query. When I change my query to
    SELECT * FROM ora:t:IDC:GlobalProfile WHERE ora:p:xqblIntranetSubGroep='Nieuws'
    so, I hardcode the value of my URL parameter in my query, the expected content items are shown.
    Also, I have another page containing a content presenter taskflow for a single item, based on the data source:
    +${'WebCenterSpaces-UCM#dDocName:'}${param.dDocName}+
    In this case, URL parameter values for dDocName are passed correctly and content presenter is showing the document with dDocName as entered in the URL.
    Does anybody have any idea on how to solve this probem?
    regards,
    Harold

    hi all
    when i try using cmis query with Arabic characters it display no results .
    SELECT * FROM ora:t:IDC:GlobalProfile WHERE AND ora:p:xAgrPressMag LIKE'جريدة الرياض'
    this is the query i am using and the value inside ora:p:xAgrPressMag is correct and i try search this value inside content presenter normal search and it display results i am afraid that cmis query doesnt accept arabic characters
    any suggestion please its top urgent
    best regards
    Edited by: 975169 on Feb 26, 2013 12:59 AM

  • How to compare date with null value

    Hi
    I have a date filed and i assigned that input box with context attribute of type Date.
    Here my problem is
    when the end user not entered any thing (null ) the i have give some defaul date.
    so first in the action method i have to check the date with null
    if it is null i have to give default date.
    so please let me know how to over come this.
    thanks
    Mukesh

    Hi
    You can get your date in your action method like
    Date newDate=new Date();
    Date myDate= wdThis
                              .wdGetYourComponentNameController()
                                      .wdGetContext()
                                           .currentYourNodeNameElement()
                                                           .getYourDateName();
    if ( myDate== null) {
             wdContext.currentContextElement().setYourDateName(newDate);
    else{...........//continue your other validations or calling other methods}
    Regards
    Abhijith YS
    Message was edited by:
            Abhijith YS

  • Native TopLink named query with named parameters

    Hello,
    Defining my metadata in native TopLink xml and using the native TopLink's Session interface I can access and successfully execute a named query using positional parameters (parameters passed to match the ?1 ?2 etc). I used for this the Session.executeQuery(String, Class, List) method e.g.
    select p from Person p where p.name = ?1
    Now, how can I get the same Session to execute named queries using named parameters? None of the Session.executeQuery methods seem suitable ... Am I missing anything here? e.g.
    select p from Person p where p.age = :age
    I can't find in Session http://www.oracle.com/technology/products/ias/toplink/doc/1013/main/b13698/oracle/toplink/sessions/Session.html a good match for this use-case. I would expect something like:
    Session.executeQuery(String queryName, Class target, List argNames, List argValues)
    or
    Session.executeQuery(String queryName, Class target, Map argsKeyedByName)
    but can't find any good match, can anyone please enlighten me?
    Thanks in advance,
    Best regards,
    Giovanni

    Hello Chris,
    Many thanks for your response. I am sorry if I did not explain my problem properly.
    Suppose I already defined a named query in the metadata XXXProject.xml using the <opm:querying ... this JPQL named query "customFinder" already exists and would look something like:
    select p from Person p where p.firstname=:firstname and p.lastname=:lastname and p.birthdate=:birthdate
    now say you want to execute this query from the Session:
    Vector args = new Vector();
    // how do you know the order? you shouldn't know the order!
    // you know only the parameter names and that's what I mean
    // about named parameters
    // This args setup is wrong ... I need a way to specify to which
    // parameter name each argument corresponds to. In other words
    // if the named query where criteria order of parameters is modified
    // perhaps because of pruning composite keys etc you won't break the
    // existing code ...
    args.add(new Date());
    args.add("Azua");
    args.add("Giovanni");
    Session session = ...
    session.executeQuery("customFinder", Person.class, args);
    JPA supports both type of queries positional parameters and named parameters. Your explanation above is only for the first, my question refers to the later.
    I have not yet found the api for this ... though I am investigating along the lines of:
    Query query = session.getQuery("customFinder");
    and then try to assign the arguments in the same order that the parameters are defined in query or?
    Thanks in advance,
    Best regards,
    Giovanni
    Edited by: bravegag on 29.05.2009 08:06

  • QUESTION:  HOW TO WRITE QUERY  WITH MANY TO MANY RELATIONSHIPS

    Could someone help me out here?
    I was sitting here looking at some tables ie table_name and synonyms and wondering.
    If a table can belong to many synonyms and a synonym can belong to many tables how would one write a query where I would like to know which tables belong to each synonym or on the other hand which synonym belongs to what tables?
    Would I try to develop an outside join for this, a corrolated query or a query with a subquery or would there be another format that would work better?
    What would be the best method of attack on this?
    Thanks for your thoughts on this.
    al

    Actually, the relationship is not many to many. A table can have many synonyms, but a synonym within a namespace (i.e. a PUBLIC synonym, or a private synonym created by a user) can only point to one table. The xxx_synonmys tables already contain the information about the table_name and table_owner.
    John

  • How too set query print layout parameters?

    Hello,
    simple task:
    1. Open "Query Print Layout...": SBO_Application.ActivateMenuItem("4868")
    2. Handle new reports form: SBO_Application.Forms.ActiveForm (I know, the better solution should be get form with proper TypeEx and highest TypeCount, but now it doesn't matter)
    3. Select row with required report: m.Columns.Item(0).Cells.Item(row).Click(BoCellClickType.ct_Regular, 0)
    4. Run printing: SBO_Application.ActivateMenuItem("519")
    5. Handle new parameters form: ???
    How can I get newly created form containing report parameters (TypeEx "4000")? I wanna set proper parameters and click "OK" to show printed report. Doesn't work handling:
    - FORM_LOAD in ItemEvent
    - MenuEvent for "519" (is only BeforeAction
    - PrintEvent (executed after accepting parameters)
    - ReportDataEvent (passed FormUID belongs to reports list, not parameters)
    In each event I've listed all forms and there is no form titled "Query - Selection Criteria" with expected TypeEx.
    Is there any way to achive this?

    when you activate print preview of printing on selected User Query Layout, you can cacth the ET_FORM_LOAD event of formTypeEx =4000
    It is working. Please note if you do not have this event, you may check your filters (?)
    Then you can populate your values. Based on my experience the click ok button is not working.
    Tip: Search the forum in year 2009 i have posted there sample codes
    Regards
    J

  • How to design constructor with variable parameters?

    I'm working on a "project" where I need to make a class "book" that can store information about a book. It's name, isbn, stock, etc... What is throwing me off a little bit is the author. I'm allowed to enter up to 4 authors per book object. I'm coming at the problem with the assumption, that I should be able to load this author data within the constructor. Questions is how. At first I thought I'd make 4 different constructors, each with a different number of author parameters. Simple enough but it seems unnecessarily messy. Then I thought I'd make a variable length parameter array. e.g book( String ... author ). But what if someone wants to enter more than 4 authors or none at all?
    QUESTION:
    Is there a way I can set a minimum and maximum of inputs for variable length paramters?
    Vectors seem like they could be useful here instead of arrays. But again there is that problem of controlling constructor parameters.

    Then I thought I'd make a variable length parameter array. e.g book( String ... author ). (Otherstuff, String author, String ... otherAuthors)
    Is there a way I can set a minimum and maximum of inputs for variable length paramters?Validate it in the code itself
    Or create another class specifically for Authors
    No matter what you do you will still need validation code, for example what if the author is null? Or empty?
         class Authors
                public String Author1;
                public String Author2;
                public String Author3;
                public String Author4;
                public Authors(String auth)
                public Authors(String auth1, String auth2)
           }

  • PL/SLQ - How to create query with horizontal running totals

    Hi:
    I'm trying to create a report in the following format
    Year Name Reg1 Reg2 Reg3
    2001 Al 3 4 5
    2001 Le 4 1 1
    2001 7 5 6
    2002 Sue 2 4 1
    2002 Al 1 3 6
    2002 Jim 6 1 3
    2002 16 15 16
    2003 Jim 4 -3 2
    2003 Le -2 4 5
    2003 20 16 23
    Note that the totals are accumulating horizontally, broken on year. How do I do that, please? Thanks very much!
    Al

    Hi, Al,
    Welcome to the forum!
    978108 wrote:
    Hi:
    I'm trying to create a report in the following format
    Year Name Reg1 Reg2 Reg3
    2001 Al 3 4 5
    2001 Le 4 1 1
    2001 7 5 6
    2002 Sue 2 4 1
    2002 Al 1 3 6
    2002 Jim 6 1 3
    2002 16 15 16
    2003 Jim 4 -3 2
    2003 Le -2 4 5
    2003 20 16 23 You may have noticed that this site normally doesn't display multiple spaces in a row.
    Whenever you post formatted text (such as query results) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    If you do that, your desired output will be much more readable:Year Name Reg1 Reg2 Reg3
    2001 Al 3 4 5
    2001 Le 4 1 1
    2001 7 5 6
    2002 Sue 2 4 1
    2002 Al 1 3 6
    2002 Jim 6 1 3
    2002 16 15 16
    2003 Jim 4 -3 2
    2003 Le -2 4 5
    2003 20 16 23
    Note that the totals are accumulating horizontally, broken on year. How do I do that, please? Thanks very much!
    AlHere's one way to do that:WITH     yearly_summary     AS
         SELECT     year
         ,     SUM (SUM (reg1)) OVER (ORDER BY year)     AS reg1
         ,     SUM (SUM (reg2)) OVER (ORDER BY year)     AS reg2
         ,     SUM (SUM (reg3)) OVER (ORDER BY year)     AS reg3
         FROM     table_x
         GROUP BY year
    SELECT     year, name, reg1, reg2, reg3
    FROM     table_x
    UNION
    SELECT     year, NULL, reg1, reg2, reg3
    FROM     yearly_summary
    ORDER BY year, name
    Edited by: Frank Kulash on Dec 20, 2012 3:04 PM
    Corrected query.
    Whenever you have a problem, please post CREATE TABLE and INSERT statements for your sample data.  For example:CREATE TABLE     table_x
    ( year     NUMBER
    , name     VARCHAR2 (10)
    , reg1     NUMBER
    , reg2     NUMBER
    , reg3     NUMBER
    INSERT INTO table_x (year, name, reg1, reg2, reg3) VALUES (2001, 'Al', 3, 4, 5);
    INSERT INTO table_x (year, name, reg1, reg2, reg3) VALUES (2001, 'Le', 4, 1, 1);
    INSERT INTO table_x (year, name, reg1, reg2, reg3) VALUES (2002, 'Sue', 2, 4, 1);
    INSERT INTO table_x (year, name, reg1, reg2, reg3) VALUES (2002, 'Al', 1, 3, 6);
    INSERT INTO table_x (year, name, reg1, reg2, reg3) VALUES (2002, 'Jim', 6, 1, 3);
    INSERT INTO table_x (year, name, reg1, reg2, reg3) VALUES (2003, 'Jim', 4,-3, 2);
    INSERT INTO table_x (year, name, reg1, reg2, reg3) VALUES (2003, 'Le', -2, 4, 5);
    Also, say which version of Oracle you're using.  In this case, it may not matter.  The query above will work in Oracle 9.1 and higher.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Query with nulls and multiple columns

    I need help with structuring a query. I have the following table:
    REGION |     AREA
    1     | A
    1     |      B
    1     |      C
    1     |      D
    1     |      (null)
    (null)     | A
    (null)     |      B
    (null)     |      C
    (null)     |      A
    2     |      A
    2     |      (null)
    I need to get the results:
    REGION |     AREA
    1     |      (null)
    (null)     | A
    (null)     |      B
    (null)     |      C
    2     |      (null)
    So really - all the regions that have a null "AREA" and all the Areas with a null "REGION" that are unique. I can do this with two separate statements but I'd like to be able to do it in one query if possible.

    user9179751 wrote:
    I need help with structuring a query. I have the following table:
    REGION |     AREA
    1     | A
    1     |      B
    1     |      C
    1     |      D
    1     |      (null)
    (null)     | A
    (null)     |      B
    (null)     |      C
    (null)     |      A
    2     |      A
    2     |      (null)
    I need to get the results:
    REGION |     AREA
    1     |      (null)
    (null)     | A
    (null)     |      B
    (null)     |      C
    2     |      (null)
    So really - all the regions that have a null "AREA" and all the Areas with a null "REGION" that are unique. I can do this with two separate statements but I'd like to be able to do it in one query if possible.SELECT REGION, AREA FROM TABLE1 WHERE REGION IS NULL OR AREA IS NULL;

Maybe you are looking for

  • Itunes not seeing all the voice memos on my iPhone 4s

    I want to sync all my voice memos from my iPhone 4s to iTunes but when I plug my phone into my macbook air, the section that says voice memos only has about 37 of the 125 voice memos I have on the phone. I also looked in the Music section, which has

  • Ipad mini

    I buy an ipad mini, I do not know how to use it! I don't have a wireless network coverage at home, I don't know how to use the software(kit) and how to connect itunes song? If I want to contact on the wireless network, what wireless router I need buy

  • Plugging in iPod dismounts USB drive-Finder copy

    I have 3 USB and 8 FireWire drives in addition to 3 internal drive connected to my Mac Pro. I am running OS X 10.5.2 and when I plug in my iPod classic (160 GB), one of my USB drives dismounts. This happened when I was copying a large amount of data

  • No "Thumbnails" View?  ?

    OK, I've labored long enough with the fundamentals... now I want to see if I can have some fun with this thing... I just plugged in an SD card reader (none built in... bummer) and loaded in a card with some photos I took this afternoon with my Nikon

  • Captivate recordings not allowing retake in KMx

    Can anyone give some insight on our dillemma? We have selected Captivate as our assessment tool inside our LMS, KMx, and we have troubleshot and troubleshot, and cannot find why sometimes the assessment allows us to retake and other times not. And, w