Querying for existing set of values

HI,
I have the following scenario. I have one table which has the measure_id,measure_value and date.
For every date, I will be populating the measure_value for every measure_id. 
If the source, doesnt have the value for a day,for a measure_id, I should update it with 0.
If the source gets fresh data for a date, then the related value should get updated(sum of values for that day) or inserted.(incremental)
DATE MeasureID MeasureValue
02/01  1 10
02/01  2 20
02/01  3 30
02/02  1 10
02/02  2 0(no data in source)
02/02  3 30
Can you please give me the best query for this scenario. Any help is appreciated.
Porus

you can try using Merge command.
I have used some sample data in Source and Destination tables.Also i used a measures table with three measure.
Declare @Source Table(Dt Date, MeasureID int, MeasureValue int);
Declare @Destination Table(Dt Date, MeasureID int, MeasureValue int);
Declare @Measure Table (MeasureID int);
Insert into @Measure select 1 union all select 2 union all select 3
Insert into @Source
select '20140201',1,10
union all
select '20140201',2,10
union all
select '20140201',3,10
union all
select '20140202',1,10
union all
select '20140202',3,30
Insert into @Destination
select '20140201',1,0
select * from @Source
select * from @Destination
;With AllMeasures
as
select * from
(SELECT distinct Dt from @Source) A
cross join @Measure
MERGE @Destination AS target
USING
select A.Dt,A.MeasureID,isnull(S.MeasureValue,0) from AllMeasures A
left join @Source S on A.Dt=S.Dt and A.MeasureID=S.MeasureID
) AS source (Dt, MeasureID,MeasureValue)
ON (target.Dt = source.Dt and target.MeasureID = source.MeasureID)
WHEN MATCHED THEN
UPDATE SET MeasureValue = source.MeasureValue
WHEN NOT MATCHED THEN
INSERT (Dt, MeasureID,MeasureValue)
VALUES (source.Dt,source.MeasureID,source.MeasureValue);
select * from @Destination
Vinay Valeti| If you think my suggestion is useful, please rate it as helpful. If it has helped you to resolve the problem, please Mark it as Answer

Similar Messages

  • How to model query for -- existing and unchanged values

    Hello BW Experts,
    I have material and material group as navigational time-dependent attributes. I have a requirement to show the existing and unchanged values for the material and material group in the time frame 2003 to 2006 . how to create a query for this.
    Suggestions appreciated.
    Thanks,
    BWer

    HI ,
    I think u need to add two more date fields as the attributes  to the master data and then use them and give restriction in the query with the Keydate to see data which has unchanged from One range to another . As key Date applies to only the system defined to and from dates present in the Master Data .
    In query give Keydate as 31.dec.2006 and then give restriction for user defined dates sa follows :
    User From : 01.01.1000 - 31.12.2002.
    User To : 01.01.2007 -- 31.12.9999 .
    Regards,
    Vijay.
    Message was edited by: vijay Kumar
    Message was edited by: vijay Kumar
    Message was edited by: vijay Kumar

  • Creating an SQL Query for Project Custom Fields Values

    Hello:
    I'm currently trying to create an SQL Query to show all of the server's Project Custom Fields Values, along with the modification date.
    So far, I've managed to display correctly all of the data for all of the Projects' text value Custom Fields (those not based on a LookUp Table) with this query:
    SELECT
    MSP_PROJECTS.PROJ_NAME,
    MSP_CUSTOM_FIELDS.MD_PROP_NAME,
    MSP_PROJ_CUSTOM_FIELD_VALUES.CODE_VALUE,
    MSP_PROJ_CUSTOM_FIELD_VALUES.TEXT_VALUE,
    MSP_PROJ_CUSTOM_FIELD_VALUES.MOD_DATE
    FROM
    MSP_PROJ_CUSTOM_FIELD_VALUES
    INNER JOIN
    MSP_CUSTOM_FIELDS
    ON MSP_CUSTOM_FIELDS.MD_PROP_UID = MSP_PROJ_CUSTOM_FIELD_VALUES.MD_PROP_UID
    INNER JOIN
    MSP_PROJECTS
    ON MSP_PROJECTS.PROJ_UID = MSP_PROJ_CUSTOM_FIELD_VALUES.PROJ_UID
    WHERE
    MSP_PROJ_CUSTOM_FIELD_VALUES.CODE_VALUE IS NULL
    ORDER BY
    MSP_PROJ_CUSTOM_FIELD_VALUES.PROJ_UID,
    MSP_PROJ_CUSTOM_FIELD_VALUES.MD_PROP_UID
    However, when I try a new Query to obtain the actual values for the Projects Custom Fields that do use a LookUp Table, I can't seem to find what table in the model I'm supposed to link to the MSP_PROJ_CUSTOM_FIELD_VALUES.CODE_VALUE field (the TEXT_VALUE
    field has NULL value when CODE_VALUE field isn't NULL)
    Any suggestions on how to obtain the actual Projects' custom fields values instead of the Code Value, for Metadata that do use a LookUp Table?
    Also, I'm able to run this query only in the Published Database, since the MSP_CUSTOM_FIELDS table is empy in the Draft Database. Why is that?
    Awaiting your kind reply,
    Sebastián Armas PMO Project Manager

    Hi Sebastián, rather than directly accessing the database it would be better to use the PSI to get this data.  Take a look at the ProjTool sample in the SDK whcih gets this data.
    Best regards,
    Brian.
    Blog |
    Facebook | Twitter | Posting is provided "AS IS" with no warranties, and confers no rights.
    Project Server TechCenter |
    Project Developer Center |
    Project Server Help | Project Product Page

  • Query for Existing Records( to improve performance)

    Hi Friends,
    I want to show only those records from A Table which is not in B Table.
    Table A--
    Ticket no Ticket date
    1 01-01-2009
    2 02-01-2009
    3 02-02-2009
    Table B---
    Ticket no Ticket date
    3 02-02-2009
    means only 1,2 should show.
    I am using EXISTS
    select ticket_no,ticket_date
    from A
    where not exists( select '1'
    from B
    where B.ticket_no=A.ticket_no
    and B.ticket_date=A.ticket_date
    is any other way to improve my query ?
    Help me out.
    KarTiK PareeK.

    SomeoneElse wrote:
    That should reduce cost up to 20%.That's doubtful.
    BTW: joins and operator sets will be much slower that EXISTS in that case.Maybe, maybe not.
    It's possible that the two queries wouldn't return the same results, so they wouldn't be comparable anyway.
    Minus also does a sort to eliminate duplicates. But maybe that's what the OP wanted.
    Of course, as usual we didn't get any sample tables, data, results...I wrote that based on my own research. I created two tables, populated them with sample data (1,000,000 rows each).
    What I wrote about 20% decrease in cost, was based on query time consumption and explain plan before and after analyzing tables.
    In my case, joins were slower. USE_* hints didn't help. MINUS was slower also.

  • Parameter Query for True or False values

    I have what seems like a painfully simple task and it has me stopped dead.  I reviewed a similar thread, and the answers there don't seem to apply. Working in Crystal 11.5 with an MS SQL database.
    I am pulling data from vwCommmittees.  There is a field in this view called IsActive.  I want to create a committee list report that will allow the user to select only the active committees or all committees.
    A SQL select statement that says where dbo.IsActive = '1' will return only the active committees.
    In Crystal reports, if I place the IsActive field on the report, it returns with "True" or "False."
    When I create a parameter for this field, I find that 1) I can't see the parameter in the report expert -- my only choices are Is any value, Is true, Is false or Formula.
    I've made several attempts to create a formula and nothing is working. It's not clear to me wheter I should be creating a static or a dynamic parameter.  When I choose boolean as the type, that doesn't seem to help.  I tried a dynamic parameter which gave me true and false values, but don't seem to work.
    Any pointers on dealing with this kind of parameter query would be greatly appreciated.
    Sincerely,
    Ridge (in New Joisey)

    Hi..
    Create a static parameter and give the default values like
    0 and 1
    In Record Selection check like..dbo.IsActive = {?parameter}
    If the above is not working for you, then create a formula
    like..
    If dbo.IsActive = '1' then
    "Active"
    Else "In Active"
    Place this formula on your report and create a static parameter with default values Active and In Active.
    In record selection filter the above.
    Thanks,
    Sastry

  • Pl.tell a query for non databsae items values as zero

    hai
    i have table like this
    emp_name     date           hours
    xxx          19-12-2007     3
    yyy          20-12-2007     4
    zzz          23-12-2007     3
    i want a query to get the data for 5 days.(ie.19 to 23)
    In that the left two days should be placed as zero in the output.
    please help me.
    thanks

    Something like:
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 'xxx' as emp_name, to_date('19-12-2007','dd-mm-yyyy') as dt, 3 as hours from dual union all
      2             select 'yyy', to_date('20-12-2007','dd-mm-yyyy'), 4 from dual union all
      3             select 'zzz', to_date('23-12-2007','dd-mm-yyyy'), 3 from dual)
      4  -- END OF TEST DATA
      5  select t.emp_name, d.dt, nvl(t.hours,0) as hours
      6  from t,
      7       (select to_date('19-12-2007','dd-mm-yyyy')+rownum-1 as dt
      8        from dual connect by rownum <= to_date('23-12-2007','dd-mm-yyyy') - to_date('19-12-2007','dd-mm-yyyy') + 1) d
      9  where d.dt = t.dt(+)
    10* order by d.dt
    SQL> /
    EMP DT                       HOURS
    xxx 19/12/2007 00:00:00          3
    yyy 20/12/2007 00:00:00          4
        21/12/2007 00:00:00          0
        22/12/2007 00:00:00          0
    zzz 23/12/2007 00:00:00          3
    SQL>

  • Querying for custom picklist values

    Hello all,
    I have created a new field on my opportunity type called "Industry" and gave it picklist values. However, the system is not allowing me to query for the values using the Picklist web service. Am I missing a step here, or does the system not allow querying for custom picklist field values? I can get to certain lists of picklist values for Opportunity (Type, Probability, some others) but not the picklist I created. Am I doing something wrong?
    Thanks!
    -Kevin Green

    Hi,
    Find integration tag for custom field in Field Setup. When you call getPicklist method, pass three values like Object type(ex: Lead), integratin tag for the custom field, "" ( this is language, this field is no need for English languague)
    Hope this willl work
    Raja Kumar Malla
    [email protected]

  • Set form value from MyQuery

    <cfif structKeyExists(MyQuery, "MyID")>
    <CFSET form.MyID= MyQuery.MyID>
    </cfif>
    <cfif structKeyExists(url, "MyID")>
    <CFSET form.MyID= url.MyID>
    </cfif>
    I use above code to check if query ID exists then assign value to my form variable.
    It seems that it does not work, but it works for url.
    Can you please help and advise are there any way to check value in query and assign to the form if it is defined?
    Your help and information is great appreciated,
    Regards,
    Iccsi,

    For assigning the value to form field you can directly use value="#MyQuery.MyID#"
    For eg:<cfform><cfif structKeyExists(MyQuery, "MyID")> <cfinput type="text" Name="MyID" value="#MyQuery.MyID#"></cfif></cfform>
    So the input text will be visible if value in query is defined else the correct data will be populated to form field MyID

  • Load values in a set of values asigned to a segment if the accounting flexfield

    Hi folks:
    I have defined an accounting flexfield with several segments. One of the is the natural account qualified as natural.
    I have to enter up to 30000 values for that set of values and I want to know if there is an script to load those values directly into the table with SQL*Plus
    I know this can not be supported but the problem is that I have to do this five times
    Any help will be useful

    Hi Jose Luis!
    Check out the following website: http://www.comstar.co.uk/dataload/
    Dataload is a tool used by many Oracle Consultants for exactly the purpose you require. You can download the tool and several templates from this site. Enjoy!
    Pat Henry

  • How to query for messages on JMS Queue?

    Hi All,
    What is the best way to query on a JMS Queue? I would like to query for messages based on values entered on a screen. Can this be achieved using the JMS Adapter or any other adapter?
    JDev : 11.1.1.4
    Thanks and Regards.

    Hi,
    I am not 100% clear on your requirement and what selection criteria you need. I would be surprised if you need the DB adapter. If you just want to query how much message are in the queue or other related queries for example related to header information then DB adapter can be used. This only works when JMS queue is stored in the database. Personally I have never come across this requirement.
    I suggest to look in more detail of the JMS adapter. The JMS adapter can be used to select (subscribe) to certain messages. Please read the below for more information:
    http://docs.oracle.com/cd/E17904_01/integration.1111/e10231/adptr_jms.htm#CJACBCHJ
    The message is automatically removed from the queue (implicit delete) the moment it is picked-up. I would not recommend deleting a message directly from the queue using DB adapter. What is the point of publishing the message in the first place?
    Thanks
    Sander

  • Input Ready Query, Variable read mode setting Only Values for InfoProvider

    Hi,
    I have a problem with Selection Variable for a BEx Query :
    - I'm working with SAP BI 7.0 support package 15
    - My query is an input ready query built for an "aggregation level" based on "real time infocube" (Planning);
    - Characteristic, I want to filter with variable, has query property Advanced->Query Execution for Filter Value Selection = Only Values in InfoProvider
    - Characteristic (info-object) has set the property: Business Explorer tab--> Query Def. Filter Value Selection as Only Values in the info-provider...
    My problem is:
    when I execute a query,
    the Select Values for Variables screen appears
    I push on the Select from List button
    and Select Values For MyCharacteristic appears...
    but it shows me all values in master data table of my characteristic instead of only values in the infoprovider!!!
    If I build a query for the Real Time Cube it works correctly, but if the query is built for the aggregation level it doesn't work!
    Could someone explain me why it doesn't work correctly?
    Thanks in advanced
    Fede

    Thanks to  Mariana Lazar
    30.03.2009 - 12:30:36 CET - Risposta by SAP     
    Dear Fede,
    Regarding the query built on aggregation level please note the following
    the aggregation level is always a Virtual Provider built other
    InfoProvider and hence it does not have the dimension table and hence
    the F4 mode D is not supported.
    Therefore when aggregation level is used in a query, F4 does not supportD-mode: 'Only Values in InfoProvider' and all master data values are
    displayed in the value list.
    Reference from the note
    984229 F4 modes for input help as of SAP NetWeaver 2004s BI
    4. Since other InfoProviders do not have a dimension table, the system
    displays only posted values if you select "Only Posted Values for
    Navigation". Otherwise, it displays the values from the master data
    table.
    Hope this should clarify your doubts. Please let me know if you have
    questions else please confirm the message at your earliest convenience.
    Thank you for your cooperation and kind regards,
    @KR@ Mariana Lazar
    Senior Support Consultant
    SAP Active Global Support
    Netweaver Business Warehouse

  • Setting default value read from user session, for an LOV in Query component

    I want to set the default value of a field in VO that participates in a named view criteria and thereby in Query component. That field is configured with an LOV by mean of a view accessor. The values are Y and N and the corresponding display strings obtained from view accessor are true and false respectively.
    I am able to set the default value by setting the value of the criteria item corresponding to that field in view criteria. I am setting the value as either Y or N and I am able to corresponding display string as per the view accessor, on the query component when it is rendered.
    I want to read the defauilt value from the ADF BC user session and set it as default value. I tried setting the values as "adf.userSession.userData.usageFlag". Iam ensuring that the attribute usageFlag is set before the view activity that has the query component is invoked. But this is ending up showing no default value in the Query component when rendered.
    Can any one let me know how to go about with this?

    I made up your table since you didn't provide some example, but I'm sure this will give you the picture:
    SQL> var run_type varchar2(1)
    SQL> exec :run_type := 'A'
    PL/SQL procedure successfully completed.
    SQL> create table my_cycles as select level cycle_id
      2                            ,      level cycle_status
      3                            from   dual connect by level <= 5;
    Table created.
    SQL> select cycle_id
      2  from   my_cycles
      3  where  case
      4           when :run_type = 'D' and cycle_status  = 1 then 1
      5           when :run_type != 'D' and cycle_status  in ( 2, 3 ) then 1
      6         end = 1;
      CYCLE_ID
             2
             3
    2 rows selected.
    SQL> exec :run_type := 'D';
    PL/SQL procedure successfully completed.
    SQL> /
      CYCLE_ID
             1
    1 row selected.
    SQL>

  • Query to set initial values

    Hi all,
    Is it possible to use queries to set initial values or change existing values?  For example, we are adding in a new sales employee that will be our sales rep for customers in a certain area.  Would it be possible to run a query that would set the Sales Employee field in the BP Master Data as this new sales rep if the customer is in that area?  If yes, what is the general process for using queries to set values in this manner (we have other things we would like to use this for as well, if its possible)?
    Thanks for the help

    Hi Todd,
    The best way to tackle this is probably to use a query to extract the business partners you wish to update and then use the Data Transfer Workbench to update the Business Partners in question.
    You could also add a Formatted Search to the Business Partner screen so all new Business Partners default to the correct Sales Person based upon territory/address or whatever criteria you like.
    Cheers,
    Sean

  • Can't Set Default Value for LOV Presentation DB Column

    I have a simple form. One of the fields is populated using a named, dynamic LOV with the following source query:
    SELECT USER_NAME DISPLAY_VALUE, USER_ID RETURN_VALUE
    FROM USER_ACCT
    ORDER BY 1
    I want the default user to be public, which is one of the possible values returned by the above query. However, I just can't find a good way to do this.
    If I put the following query in the Default section, nothing happens.
    SELECT USER_ID
    FROM USER_ACCT
    WHERE USER_NAME = 'PUBLIC'
    If I look up the ID and statically put the value in the Default, it works (This isn't acceptable . From environment to environment the value will differ)
    If I put the SQL in an after footer page process, it sets the value correctly in the session but, does not update the display.
    If I try to put it in the Post Calculation Computation section, it merely produces an error.
    I'm sure that I am missing something simple but, I have not spent an hour and half on this.
    Someone please help!
    -Joe

    A function I'd like to see is the ability to not only create a select list dynamically, but also set the default value of that select list's item to the first (or Nth?) value on that list. This could be specified in the builder by an item option.
    E.G., if a select list LOV returns three values: "foo", "bar", "baz", go ahead and set the value of the select list item to "foo".
    As far as I've been able to discover, there's no built-in way to do this in Application Express. I've looked through the app, the docs, and the forum. If such a method does exist, please let me know.
    Otherwise, we end up running additional processes that reissue the query so we can grab the first item as the default value. This seems inefficient to me.
    Keeping the LOV query and the "first item" query consistent can present problems as well. We usually end up pushing the LOV query into a function so it can be maintained in a single location, but this seems more like a workaround than anything else.
    While the query is probably cached, Application Express has that return value already, right? Why calculate/choose it again?

  • CRM R12.0.6  Map Type does not exist in the value set

    Hi Everyone
    When attempting to access Service Request Types in our CRM UAT Release 12.0.6 environment an error message appears referring to 'Value General for the flexfield segment does not exist in the value set'.
    Checked the flexfields for the value set but did not set up a value for MAP_TYPES
    Checked our PROD environment but no value set up as above.
    Currently in progress of mapping service requests to responsibilites in UAT, could this be the cause and how to resolve? No mapping as yet for service requests set up in PROD. Has anyone else experienced this?
    Thanks very much, Louise

    Hi IWolbers,
    >>I have a recurring problem where all of a sudden I can no longer see the values of my variables when I debug my unit tests. I cannot find a pattern as to when this happens but I experience this across one of every 20 tests that I write. Occasionally
    this has also happened during normal debbuging of running code on my machine.
    So you mean that it worked well before, am I right? 
    If you debug the same app in other VS machine, does it work well? So we could make sure that whether it is related to the VS IDE.
    Please disable all add-ins in your VS IDE, and then reset your VS settings, debug it again.
    https://msdn.microsoft.com/en-us/library/ms247075(v=vs.100).aspx
    Or you could run your VS in safe mode, debug it again, at least, we could know that whether it is the add-in's issue.
    https://msdn.microsoft.com/en-us/library/ms241278.aspx
    To make sure that it is not the project files' issue, create a new blank solution, copy the project files to the new solution, clean and rebuild the solution, check the result.
    >>Once I step over this to the next line (screen shot 2) I get the error message 'The name '[variable name]' does not exist in the current context'
    How about debugging it with "Step Into" instead of "Step Over"? Or you could add breakpoints between 234 line to 241 line, after the breakpoint is hit, check the watch window again. How about the result?
    In addition, do you check other debugger window like local or others?
    Best Regards,
    Jack
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for