Query Reference Data and CFCs

I would to run a  query once that returns a record set and pass that as reference data to functions in a ColdFusion component. Inside those functions, I'd take the query and run a query of queries for aggregate results among other things. Can this be done? I am getting an error basically saying the passed-in query is not a simple value where I use it in the FROM clause of the query.
It works fine when both queries are within the same function, but it's needless overhead to continually get the same ref data.
Example:
template.cfm
<cfobject name="lib" component="mycfc">
<cfinvoke component="#lib#" method="getQueryRefData" returnvariable="refData" />
<cfinvoke component="#lib#" method="getSum" returnvariable="sum" refdata="#refData#" />
mycfc.cfc
<cffunction name="getQueryRefData" access="public" returntype="query">
        <cfquery name="allData" datasource="myDatasource">
            SELECT * FROM answer
        </cfquery>
        <cfreturn allData>
</cffunction>
<cffunction name="getSum" access="public" returntype="numeric">
     <cfargument name="refData" type="query" required="yes">
     <cfquery name="deptSum" dbtype="query">
            SELECT COUNT(*) AS total, department
            FROM ARGUMENTS.refData <--- ERROR occurs here --->
            GROUP BY department
      </cfquery>
      <cfreturn Val(deptSum.total)>
</cffunction>

This works when I run it.
<cffunction name="q_of_q" returntype="query">
<cfargument name="QueryIn" type="query">
<cfquery name="QueryOut" dbtype="query">
select count(*) thecount
from arguments.queryin
</cfquery>
<cfreturn QueryOut>
</cffunction>
<cfquery name="x" datasource="burns">
select 1 f1 from dual
</cfquery>
<cfset abc = q_of_q(Queryin = x)>
<cfdump var="#abc#" label="abc">
Try it and if it works, start modifying it until it either does what you want it to do, or crashes.

Similar Messages

  • I need to pass a query in form of string to DBMS_XMLQUERY.GETXML package...the parameters to the query are date and varchar ..please help me..

    I need to pass a query in form of string to DBMS_XMLQUERY.GETXML package...the parameters to the query are date and varchar ..please help me build the string .Below is the query and the out put. ( the string is building fine except the parameters are with out quotes)
    here is the procedure
    create or replace
    procedure temp(
        P_MTR_ID VARCHAR2,
        P_FROM_DATE    IN DATE ,
        P_THROUGH_DATE IN DATE ) AS
        L_XML CLOB;
        l_query VARCHAR2(2000);
    BEGIN
    l_query:=  'SELECT
        a.s_datetime DATETIME,
        a.downdate Ending_date,
        a.downtime Ending_time,
        TO_CHAR(ROUND(a.downusage,3),''9999999.000'') kWh_Usage,
        TO_CHAR(ROUND(a.downcost,2),''$9,999,999.00'') kWh_cost,
        TO_CHAR(ROUND(B.DOWNUSAGE,3),''9999999.000'') KVARH
      FROM
        (SELECT s_datetime + .000011574 s_datetime,
          TO_CHAR(S_DATETIME ,''mm/dd/yyyy'') DOWNDATE,
          DECODE(TO_CHAR(s_datetime+.000011574 ,''hh24:'
          ||'mi''), ''00:'
          ||'00'',''24:'
          ||'00'', TO_CHAR(s_datetime+.000011574,''hh24:'
          ||'mi'')) downtime,
          s_usage downusage,
          s_cost downcost
        FROM summary_qtrhour
        WHERE s_mtrid = '
        ||P_MTR_ID||
       ' AND s_mtrch   = ''1''
        AND s_datetime BETWEEN TO_DATE('
        ||P_FROM_DATE||
        ',''DD-MON-YY'') AND (TO_DATE('
        ||P_THROUGH_DATE||
        ',''DD-MON-YY'') + 1)
        ) a,
        (SELECT s_datetime + .000011574 s_datetime,
          s_usage downusage
        FROM summary_qtrhour
        WHERE s_mtrid = '
        ||P_MTR_ID||
        ' AND s_mtrch   = ''2''
        AND s_datetime BETWEEN TO_DATE('
        ||P_FROM_DATE||
        ',''DD-MON-YY'') AND (TO_DATE('
        ||P_THROUGH_DATE||
        ','' DD-MON-YY'') + 1)
        ) B
      where a.S_DATETIME = B.S_DATETIME(+)';
    SELECT DBMS_XMLQUERY.GETXML('L_QUERY') INTO L_XML   FROM DUAL;
    INSERT INTO NK VALUES (L_XML);
    DBMS_OUTPUT.PUT_LINE('L_QUERY IS :'||L_QUERY);
    END;
    OUTPUT parameters are in bold (the issue is they are coming without single quotes otherwise th equery is fine
    L_QUERY IS :SELECT
        a.s_datetime DATETIME,
        a.downdate Ending_date,
        a.downtime Ending_time,
        TO_CHAR(ROUND(a.downusage,3),'9999999.000') kWh_Usage,
        TO_CHAR(ROUND(a.downcost,2),'$9,999,999.00') kWh_cost,
        TO_CHAR(ROUND(B.DOWNUSAGE,3),'9999999.000') KVARH
      FROM
        (SELECT s_datetime + .000011574 s_datetime,
          TO_CHAR(S_DATETIME ,'mm/dd/yyyy') DOWNDATE,
          DECODE(TO_CHAR(s_datetime+.000011574 ,'hh24:mi'), '00:00','24:00', TO_CHAR(s_datetime+.000011574,'hh24:mi')) downtime,
          s_usage downusage,
          s_cost downcost
        FROM summary_qtrhour
        WHERE s_mtrid = N3165 AND s_mtrch   = '1'
        AND s_datetime BETWEEN TO_DATE(01-JAN-13,'DD-MON-YY') AND (TO_DATE(31-JAN-13,'DD-MON-YY') + 1)
        ) a,
        (SELECT s_datetime + .000011574 s_datetime,
          s_usage downusage
        FROM summary_qtrhour
        WHERE s_mtrid = N3165 AND s_mtrch   = '2'
        AND s_datetime BETWEEN TO_DATE(01-JAN-13,'DD-MON-YY') AND (TO_DATE(31-JAN-13,' DD-MON-YY') + 1)
        ) B
      where a.S_DATETIME = B.S_DATETIME(+)

    The correct way to handle this is to use bind variables.
    And use DBMS_XMLGEN instead of DBMS_XMLQUERY :
    create or replace procedure temp (
      p_mtr_id       in varchar2
    , p_from_date    in date
    , p_through_date in date
    is
      l_xml   CLOB;
      l_query VARCHAR2(2000);
      l_ctx   dbms_xmlgen.ctxHandle;
    begin
      l_query:=  'SELECT
        a.s_datetime DATETIME,
        a.downdate Ending_date,
        a.downtime Ending_time,
        TO_CHAR(ROUND(a.downusage,3),''9999999.000'') kWh_Usage,
        TO_CHAR(ROUND(a.downcost,2),''$9,999,999.00'') kWh_cost,
        TO_CHAR(ROUND(B.DOWNUSAGE,3),''9999999.000'') KVARH
      FROM
        (SELECT s_datetime + .000011574 s_datetime,
          TO_CHAR(S_DATETIME ,''mm/dd/yyyy'') DOWNDATE,
          DECODE(TO_CHAR(s_datetime+.000011574 ,''hh24:'
          ||'mi''), ''00:'
          ||'00'',''24:'
          ||'00'', TO_CHAR(s_datetime+.000011574,''hh24:'
          ||'mi'')) downtime,
          s_usage downusage,
          s_cost downcost
        FROM summary_qtrhour
        WHERE s_mtrid = :P_MTR_ID
        AND s_mtrch   = ''1''
        AND s_datetime BETWEEN TO_DATE(:P_FROM_DATE,''DD-MON-YY'')
                           AND (TO_DATE(:P_THROUGH_DATE,''DD-MON-YY'') + 1)
        ) a,
        (SELECT s_datetime + .000011574 s_datetime,
          s_usage downusage
        FROM summary_qtrhour
        WHERE s_mtrid = :P_MTR_ID
        AND s_mtrch   = ''2''
        AND s_datetime BETWEEN TO_DATE(:P_FROM_DATE,''DD-MON-YY'')
                           AND (TO_DATE(:P_THROUGH_DATE,'' DD-MON-YY'') + 1)
        ) B
      where a.S_DATETIME = B.S_DATETIME(+)';
      l_ctx := dbms_xmlgen.newContext(l_query);
      dbms_xmlgen.setBindValue(l_ctx, 'P_MTR_ID', p_mtr_id);
      dbms_xmlgen.setBindValue(l_ctx, 'P_FROM_DATE', to_char(p_from_date, 'DD-MON-YY'));
      dbms_xmlgen.setBindValue(l_ctx, 'P_THROUGH_DATE', to_char(p_through_date, 'DD-MON-YY'));
      l_xml := dbms_xmlgen.getXML(l_ctx);
      dbms_xmlgen.closeContext(l_ctx);
      insert into nk values (l_xml);
    end;

  • Notification - Reference Date and Time

    I require the Reference Date and Reference Time (populated while Completing the Notification) to be available on the Notification Screen in ISU.
    Will any config setting allow me to display this field on the Notification screen (IW53)? None of the available Screen Areas seem to have this field.

    Hi Abhishek,
    The name of the exit is EXIT_SAPMIWO0_020. Its a part of the function group XQQM which is a group containing all Customer Exits QM/PM Notifications.
    You can go to transaction se37 and give the exit name. You will see an include named ZXQQMU20. You have to write the code here, inside the include. If system does not allow you to go inside the include and displays a message (yellow warning message at the status bar), then use transaction CMOD, use a project that is currently created in the system or a new project whichever is ok with you. Then click on Enhancement push button. Select the exit name and activate. Now you can write code inside the include ZXQQMU20.
    If this helps, <<removed by moderator>>
    Thanks.
    Bhanu
    Edited by: kishan P on Aug 31, 2010 3:25 PM

  • Query: System date and time.

    hi all,
    Does any one know how to get the System Date and System Time using query. This is for my Formatted search.
    Thanks In advance.
    Bruce.

    if you are using SQL Server
    SELECT GetDate()

  • Need help in framing an SQL query - Sample data and output required is mentioned.

    Sample data :
    ID Region State
    1 a A1
    2 b A1
    3 c B1
    4 d B1
    Result should be :
    State Region1 Region2
    A1 a b
    B1 c d

    create table #t (id int, region char(1),state char(2))
    insert into #t values (1,'a','a1'),(2,'b','a1'),(3,'c','b1'),(4,'d','b1')
    select state,
     max(case when region in ('a','c') then region end) region1,
      max(case when region in ('b','d') then region end) region2
     from #t
     group by state
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Timezone effects on Date and Timestamp fields in af:query component

    Hello,
    I'm working on an ADF application where time zone is configured as follows:
    * Dynamic View Layer time zone is configured in trinidad-config.xml file and bound to a session scoped value:
    <trinidad-config>
      <skin-family>fusionFx</skin-family>
      <time-zone>#{sessionScope.tz}</time-zone>
    </trinidad-config>* ADF BC time zone is configured in adf-config.xml file and bound to View Layer time zone:
    <adf-config>
      <user-time-zone-config xmlns="http://xmlns.oracle.com/adf/usertimezone/config">
        <user-timezone expression="#{adfFacesContext.timeZone.ID}"/>
      </user-time-zone-config>
    </adf-config>The problem here is that Dates and Timestamp values work as expected all over the application except for the af:query component. When displayed as af:inputDate in af:form, Dates and Timestamp values are NOT getting converted to the time zone (TZ) configured in trinidad-config.xml file, whereas TimestampTz and TimestampLtz are. However, when displayed in af:query component, Dates and Timestamp values are automatically converted to View Layer TZ after a search has been performed.
    For example, say View Layer TZ = US/Pacific and we enter 01/jun/2011 as a search criteria of type Date and then click on the Search button. The displayed value automatically changes to 25/nov/2011, that is, it gets converted to the WLS JVM time zone, which is set to Europe/London.
    Is conversion of Date and Timestamps in af:query component the expected behaviour or could this be a bug?
    Is there any way to avoid this conversion?
    Thanks in advance
    Version:
    ADF Business Components 11.1.1.59.23
    Java(TM) Platform 1.6.0_21
    Oracle IDE 11.1.1.4.37.59.23
    PMD JDeveloper Extension 4.2.5.3.0
    Repost on 26-nov-2011 9:29
    Repost on 28-nov-2011 15:10
    Edited by: Barbara Gelabert on 26-nov-2011 9:29
    Edited by: Barbara Gelabert on 28-nov-2011 15:10

    Hi,
    Thanks for your reply. This certainly seems promising. However, I am getting a connection error now.
    The following...
    jar_loaded = require 'ojdbc14.jar'
    puts "Oracle jar loaded? #{jar_loaded}"
    puts "Starting active record"
    require 'rubygems'
    gem 'activerecord'
    gem 'activerecord-oracle_enhanced-adapter'
    require 'activerecord'
    puts "Connecting to MXGN"
    ActiveRecord::Base.establish_connection(
    :adapter => 'oracle_enhanced',
    :host => 'THEHOST',
    :port => '1550',
    :database => 'THEDB',
    :username => 'THEUSER',
    :password => 'THEPASSWORD'
    ... produces
    Oracle jar loaded? true
    Starting active record
    Connecting to MXGN
    ERROR: ActiveRecord oracle_enhanced adapter could not load Oracle JDBC driver. Please install ojdbc14.jar library.
    ERROR: ActiveRecord oracle_enhanced adapter could not load Oracle JDBC driver. Please install ojdbc14.jar library.
    C:/jruby/jruby-1.2.0/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/connection_specification.rb:76:in `establish_connection': Please install the oracle_enhanced adapter: `gem install activerecord-oracle_enhanced-adapter` (LoadError) (RuntimeError)
    from H:\sandbox\DBPlay\lib\main_enhanced.rb:12
    I'm confused. Am I missing the driver, or have I failed to setup the enhanced Oracle adapter?
    I have tried moving the jar to $JRUBY_HOME/lib too, but the result was the same.
    All help would be greatly appreciated.
    Many Thanks
    Adrian

  • How to access reference data in BPS Exit Function

    Hi Experts,
    Can any please tell me how to access reference data in BPS Exit function. I am creating a copy function using ABAP Exit Function (Std copy and fox formula doesn't work for my requirement).
    Please suggest,
    Thanks in advance,
    Shiwesh

    Hi Deepti,
    Thanks a lot for your reply. xth_data contains all the data based on package filteration. Let me explain you,
    Say, I have a characteristic char and whose value is 'A', I want to change it to 'B' in my copy function, while keeping the original record with 'A' as well. So now I want my xth_data to contain two records, one with A and other with 'B'. I mean to say from value is 'A' and to value is 'B'. Now my package contains 'B' (the to value) as the allowed value, but not A because in the package I am setting this using a BPS variable. There are two types of variables, one is to variables other is from variable. There could be two scenarios,
    1. If I set from varibale in the package: if I do so, I will have the data in xth_data containing 'A' as char value. But in this case when I change it to 'B' and try to save both the records, package won't recognize the record with value 'B' and reject it.
    2. If I set to variable in the package: In this case the xth_data itself will not contain anything and I can not loop over xth_data because there is no record with 'B'. Only record available in the system is with 'A' values.
    That is why I am thinking about having reference daya somewhere. I could loop over reference data and then pass it to xth_data. Package will contain to variable so it will allow all my modifications to get saved.
    Thanks and regards,
    Shiwesh

  • KE28 with" Copy Characteristic Value with Reference Data" doesn't work

    Hi experts:
    We need to make a top-down setting the processing option 'Copy Characteristic Value with Reference Data'. We have the following source data:
    Customer Business Unit  Value field.
    6        #              100
    On the other hand, we have plan data as reference data:
    Customer Business Unit  Value field.
           A              40
           C              40
           D              20
    We need to run a top-down to distribute from client to Business Unit but copying client of reference data. Then, we set 'Copy Characteristic Value with Reference Data' and, in the selection criteria we set '*' for customer.
    After running, the result is that the system can find 1 sender and 3 receivers. It is exactly what we are expecting. However, program doesn't make individual items and anything is distributed.
    We have found notes 1086282 and 1273924 but the result is the same after implementing these notes.
    Thanks in advance for your help.
    Best regards
    Jose

    There are some restrictions on the XML Schema format that you can report off of in Crystal Reports.
    If you're using the ODBC XML driver, you may find this of relevance:
    [http://resources.businessobjects.com/support/communitycs/TechnicalPapers/cr_xml_data_sources.pdf|http://resources.businessobjects.com/support/communitycs/TechnicalPapers/cr_xml_data_sources.pdf]
    and if you're using the native XML driver, the following gives a guide for the accepted formats:
    [http://resources.businessobjects.com/support/communitycs/TechnicalPapers/cr_xi_native_xml_driver.pdf|http://resources.businessobjects.com/support/communitycs/TechnicalPapers/cr_xi_native_xml_driver.pdf]
    Sincerely,
    Ted Ueda

  • SEM-BPS Distribution with Reference Data

    All,
    Our planning design is such that our plan values are in one cube and our actuals are in another.  We use a mult-planning area to tie the two together.
    One of our requirements is distribute planning values from one cost center to other cost centers, but to use the actual data on the receiving cost centers as the base.  I have been able to accomplish this with the allocation function, but we need to retain the sender values.  I have been trying to use the Distribute by Reference Data from Sender to Recipient planning function, but it's not reading the reference data correctly.
    Does anybody have some insight into this function?
    Thanks
    Kory

    Hi Mary,
    Thanks for the reply.  I had ran it in trace mode and the message was that there was not any reference data; and maybe this is where I'm misunderstanding this planning function.
    Here's the scenario:  I have a cost center and a cost element and want to allocate it to another cost center.  The reference characteristic from the actuals cube that I'm using is cost element.  For example, cost center 4720001 and cost element 990039 have $100 in the planning cube.  I want to distribute this amount to cost centers 4720002 and 4720003, but using cost element 990014 as the reference data from the actuals cube.  Cost centers 4720002 and 4720003 have $200 and $500 posted to cost element 990014, respectively.  So I'm expecting 4720002 to receive $28.57 and 4720003 to receive $71.43.  When I run the function, I get a message for the receiving records stating that no reference data exists.  I have created this using the allocation planning function with success, but we also need to retain the sender values and the allocation function does not do this.
    Any further insight you have is much apreciated.
    Thanks
    Kory

  • InfoSet Query no data returned

    Hi,
    I've created InfoSet Query and Query respectively for the same InfoSet. However, only Query returns data and the InfoSet Query returns no data.
    Best regards,
    ts

    Hi Venkat,
    This is BW forum and never post/include your issue in other threads.
    if your facing problem about plant data then please post your issue at SAP MM forum.
    MM forum link can find below link.
    SCN Site Index 
    How to create a discussion:
    http://scn.sap.com/docs/DOC-46003
    Thanks

  • Inserting "Reference Data" tab in CIC Complaints / Item Details

    Dear all,
    When entering in CIC (WinGUI), and choosing the operation "Complaint", in the correspondent view "Item Details", the tab "Reference Data" is missing. This doesn't happen outside CIC0 (e.g. trx. CRMD_BUS2000126 - Maintain Activities).
    We followed the indications in some similar SAP Notes and performed some adjustments but still need help to complete the solution:
    1>Start transaction CRMV_SSC.
    2>Click the Radio button for 'complete tabstrip assignment of panel'.
    3>click the "Edit' button.
    4>Create a new entry by clicking on 'New entries' button.
    5>fill in the following details:
    - Profile type : TCPL
    - Screen Profile:CMPL_CIC
    - Tabstrip Panel:CMPL_IL_T1
    - Tabstrip:35
    - Function Code:CMPL_IT_REF - that is the function used by the Profile Type “COMP” used outside CIC0
    Subscreen:7292 - that is the subscreen used by the Profile Type “COMP” used outside CIC0
    - Program Name:SAPLCRM_SALES_UI, but an error message is shown (“Program SAPLCRM_SALES_UI cannot be used”). Also, we don’t find the previous function and screen in other programs.
    The same adjustments should also be made for “Tabstrip Panel:CMPL_IL_TC”
    So, there are 2 possible approaches:
    - How can we define the profile type "COMP" to be used inside CIC0, when a complaint is called?
    - Is it possible to find a program / screen that has the "reference data" and it is available for TCPL Profile Type?
    Thanks in advance,
    Joao

    Hi Bharat,
    1) Make the OK_CODE record as the last entry for all screens.. this means the subroutine should be called for OK_CODE at the last for a screen..
    2) what is this value '04/05' you have used for BDC_CURSOR???
    Thanks and Best Regards,
    Vikas Bittera.

  • Reference Data - self provided

    Hi
    Just starting to work my way through this - is it possible to set up reference data from anywhere other than Azure? Say for example I had an internally maintained list of Product Names I wanted to use as lookup for reference data, how could I reference
    that (other than by repeatedly importing it from Excel)?
    To add complexity, can SSDQS talk to Master Data Services? (and if not... why not?)
    Cheers, James
    James Beresford @ www.bimonkey.com
    SSIS / MSBI Consultant in Sydney, Australia
    SSIS ETL Execution Control and Management Framework @
    SSIS ETL Framework on Codeplex

    Hi James,
    Thank you for your comments and questions.
    1. MDS does "talk" to DQS, via the MDS Excel add-in. The Excel add-in has a built-in functionality to de-duplicated its records, and this is done via DQS. You can either use a pre-defined KB in the DQS server, or a default KB that we will create on the fly
    based on your Excel data.
    2. As for using reference data - there are three ways to go about doing that, only two available now.
      a. Onboard this data into your knowledge base via import or via knowledge discovery. This way the domain in the KB will contain all your reference data, and you can use this for cleansing or matching purposes. This is the easiest, swiftest way of
    doing that.
      b. Create a service and onboard it to DataMarket. The service itself does not need to be running on Azure - you can host it yourself. This is what was done by our current reference data providers (MelissaData, CDyne, Digital Trowel and Loqate, which
    you can see under the data quality services category). There is an API for doing that will soon be published for general availability. This is especially relevant if you feel that your data may be relevant for additional users, and so you may want to onboard
    it to datamarket for public consumption.
      c. (To be available in the next update of DQS) - create a "private" reference data service, and hook it directly to DQS (via the "direct" section in the reference data setting tabs in the DQS configuration. Again, this API has not yet been publicly
    released, we are currently working on finalizing it and will provide updates later on.
    Right now, it seems that the best solution for what you're trying to do would be a, but we are planning on improving this capability soon.
    Thanks,
    Elad 

  • Transaction PEPM (Profile Matchup) - Reference date problem

    I've got a problem when running the PEPM transaction. If I run the program and use a future reference date, and selects person, along the org. structure, persons who have left the company is still being displayed = assigned to the positions..
    If I search for persons in transaction PPPM along the org. structure with a future reference date, it does not display the persons who have left the company.
    Any ideas on how to solve this?
    Thanks!
    //Per

    Hi Per,
    check TC PEPM, with JOB & Person,
    May be the position, you are trying was exist in the same Org.structure since long, and it is tracking all the details linked with the respective Position.
    Yes, you are right -  In the TC PPPM, it won't show the withdrawn employees.
    try with JOB &  Person.
    Cheers,
    TG

  • Extracting current balance at previous reference date

    Hello everyone,
    I have an analyses for extracting current balance (in local currency) for some products at current day (i.e today 19 July 2013). In this interogation, I added a new dimension custom in edit formula like: TIMESTAMPADD(SQL_TSI_DAY, -1, "Dim Time"."Reference Date"). Very well, returns me the date from yesterday-18 July 2013. For a dimension measures (current balance lcy) I edited it like: FILTER("Balances"."Total Balance Lcy" USING ((TIMESTAMPADD(SQL_TSI_DAY, -1, "Dim Time"."Reference Date")))) and it didn't work.
    Overall, into the report with reference date today, I want as result the current balance for yesterday.
    Could you help me with my issue.
    Thanks!

    Advantage ? No !!! Just to get correct result..
    { =ToDate(RelativeDate(CurrentDate();-DayNumberOfMonth(CurrentDate()));"MM/dd/yy") }
    returns wrong date because, we need to deduct total days of that month from last day of that month to get a last date of previous month. So we should use
    {=ToDate(RelativeDate(LastDayOfMonth(CurrentDate());-DayNumberOfMonth(LastDayOfMonth(CurrentDate())));"MM/dd/yy") }
    Year!!!
    whats the logic behind this
    =If DayName(Year-1)<" Then FormatDate(RelativeDate(Year-1;-7);"yyyyww") Else FormatDate(Year-1;"yyyyww")
    If you follow following formulas, it gives correct result
    Year1
    =RelativeDate(CurrentDate();-DayNumberOfYear(CurrentDate()))
    Last Saturday (Year1)
    =If DayName(Year1) = "Friday" Then RelativeDate(Year1;-6) ElseIf DayName(Year1) = "Thursday" Then RelativeDate(Year1;-5) ElseIf DayName(Year1) = "Wednesday" Then RelativeDate(Year1;-4) ElseIf DayName(Year1) = "Tuesday" Then RelativeDate(Year1;-3) ElseIf DayName(Year1) = "Monday" Then RelativeDate(Year1;-2) ElseIf DayName(Year1) = "Sunday" Then RelativeDate(Year1;-2) Else RelativeDate(Year1;0)
    Repeat above for last 9 year.
    Quarter !!! I am thinkin on this
    --Kuldeep
    Edited by: Kuldeep Chitrakar on Sep 7, 2009 3:41 PM

  • Query to find the difference between the last date and the second to the last date

    Hi all,
    Hope all is well.
    I am working on the following problem because I am trying to improve my MS SQL skills. But I am stuck at the moment and I wonder if you could provide some assistance please. Here is the issue:
    Table 1: Dividends
    divId
    ExDate
    RecordDate
    PayDate
    Amount
    Yield
    symId
    1
    2013-02-19
    2013-02-21
    2013-03-14
    0.23
    0.00000
    3930
    2
    2012-11-13
    2012-11-15
    2012-12-13
    0.23
    0.00849
    3930
    3
    2012-08-14
    2012-08-16
    2012-09-13
    0.20
    0.00664
    3930
    4
    2012-05-15
    2012-05-17
    2012-06-14
    0.20
    0.00662
    3930
    5
    2012-02-14
    2012-02-16
    2012-03-08
    0.20
    0.00661
    3930
    6
    2011-11-15
    2011-11-17
    2011-12-08
    0.20
    0.00748
    3930
    7
    2011-08-16
    2011-08-18
    2011-09-08
    0.16
    0.00631
    3930
    8
    2011-05-17
    2011-05-19
    2011-06-09
    0.16
    0.00653
    3930
    9
    2011-02-15
    2011-02-17
    2011-03-10
    0.16
    0.00594
    3930
    10
    2010-11-16
    2010-11-18
    2010-12-09
    0.16
    0.00620
    3930
    11
    2010-08-17
    2010-08-19
    2010-09-09
    0.13
    0.00526
    3930
    12
    2010-05-18
    2010-05-20
    2010-06-10
    0.13
    0.00455
    3930
    13
    2010-02-16
    2010-02-18
    2010-03-11
    0.13
    0.00459
    3930
    Table 2: Tickers
    symId
    Symbol
    Name
    Sector
    Industry
    1
    A
    Agilent Technologies Inc.
    Technology
    Scientific & Technical Instruments
    2
    AA
    Alcoa, Inc.
    Basic Materials
    Aluminum
    3
    AACC
    Asset Acceptance Capital Corp.
    Financial
    Credit Services
    4
    AADR
    WCM/BNY Mellon Focused Growth ADR ETF
    Financial
    Exchange Traded Fund
    5
    AAIT
    iShares MSCI AC Asia Information Tech
    Financial
    Exchange Traded Fund
    6
    AAME
    Atlantic American Corp.
    Financial
    Life Insurance
    7
    AAN
    Aaron's, Inc.
    Services
    Rental & Leasing Services
    8
    AAON
    AAON Inc.
    Industrial Goods
    General Building Materials
    9
    AAP
    Advance Auto Parts Inc.
    Services
    Auto Parts Stores
    10
    AAPL
    Apple Inc.
    Technology
    Personal Computers
    11
    AAT
    American Assets Trust, Inc.
    Financial
    REIT - Office
    12
    AAU
    Almaden Minerals Ltd.
    Basic Materials
    Industrial Metals & Minerals
    I am trying to check the last date (i.e. max date) and also check the penultimate date (i.e. the second to the last date).  And then find the difference between the two (i.e. last date minus penultimate
    date).
    I would like to do that for each of the companies listed in Table 2: Tickers.  I am able to do it for just one company (MSFT) using the queries below:
    SELECT
    [First] = MIN(ExDate),
    [Last] = MAX(ExDate),
    [Diff] = DATEDIFF(DAY, MIN(ExDate), MAX(ExDate))
    FROM (
    SELECT TOP 2 Dividends.ExDate
    FROM Dividends, Tickers
    WHERE Dividends.symId=Tickers.symId
    AND Tickers.Symbol='MSFT'
    ORDER BY ExDate DESC
    ) AS X
    Outputs the following result:
    First
    Last
    Diff
    2012-11-13
    2013-02-19
    98
    But what I would like instead is to be able to output something like this:
    Symbol
    First
    Last
    Diff
    MSFT
    2012-11-13
    2013-02-19
    98
    AAN
    2012-11-13
    2012-12-14
    1
    X
    2012-11-13
    2012-12-14
    1
    Can anyone please let me know what do I need to add on my query in order to achieve the desired output?
    Any help would be greatly appreciated.
    Thanks in advance. 

    Could you try this?
    create table Ticker (SymbolId int identity primary key, Symbol varchar(4))
    insert into Ticker (Symbol) values ('MSFT'), ('ORCL'), ('GOOG')
    create table Dividend (DividendId int identity, SymbolId int constraint FK_Dividend foreign key references Ticker(SymbolId), ExDate datetime, Amount decimal(18,4))
    insert into Dividend (SymbolId, ExDate, Amount) values
    (1, '2012-10-1', 10),
    (1, '2012-10-3', 1),
    (1, '2012-10-7', 7),
    (1, '2012-10-12', 2),
    (1, '2012-10-23', 8),
    (1, '2012-10-30', 5),
    (2, '2012-10-1', 10),
    (2, '2012-10-6', 1),
    (2, '2012-10-29', 7),
    (3, '2012-10-1', 22),
    (3, '2012-10-3', 21),
    (3, '2012-10-7', 3),
    (3, '2012-10-12', 9)
    WITH cte
    AS (SELECT t.Symbol,
    d.ExDate,
    d.Amount,
    ROW_NUMBER()
    OVER (
    partition BY Symbol
    ORDER BY ExDate DESC) AS rownum
    FROM Ticker AS t
    INNER JOIN Dividend AS d
    ON t.SymbolId = d.SymbolId),
    ctedate
    AS (SELECT Symbol,
    [1] AS maxdate,
    [2] AS penultimatedate
    FROM cte
    PIVOT( MIN(ExDate)
    FOR RowNum IN ([1],
    [2]) ) AS pvtquery),
    cteamount
    AS (SELECT Symbol,
    [1] AS maxdateamount,
    [2] AS penultimatedateamount
    FROM cte
    PIVOT( MIN(Amount)
    FOR RowNum IN ([1],
    [2]) ) AS pvtquery)
    SELECT d.Symbol,
    MIN(MaxDate) AS maxdate,
    MIN(penultimatedate) AS penultimatedate,
    DATEDIFF(d, MIN(penultimatedate), MIN(MaxDate)) AS numberofdays,
    MIN(MaxDateAmount) AS maxdateamount,
    MIN(penultimatedateAmount) AS penultimatedateamount,
    MIN(MaxDateAmount) - MIN(penultimatedateAmount) AS delta
    FROM ctedate AS d
    INNER JOIN cteamount AS a
    ON d.Symbol = a.symbol
    GROUP BY d.Symbol
    ORDER BY d.Symbol
    Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers.
    Thanks!
    Aalam | Blog (http://aalamrangi.wordpress.com)

Maybe you are looking for

  • [Solved] Random Freezes Requiring Manual Power off

    Since I built this system, I've been getting random freezes that force me to have to manually power off and back on the entire system.  I have no idea what's causing it and I've tried everything under the sun that I can think of to resolve it to no a

  • Shared excel workbook, wont be shared -

    Hi We have a Sharepoint 2010 in our domain, and many of our users would like to edit on the same documents and excel spreadsheets.  The documents are no problem. If user A open a doc and then user B, they both can edit on the same documents, and also

  • Filter in alv grid

    Hi All,    I developed alv report.I took one filed status(8) type c. And put wa_final-status ='normal' or 'abnormal'  depend on conditon. it is hardcode. In my grid it is comming. but when I filter and select either 'normal' or 'abnormal' then it is

  • How to keep high res when I create a pdf from Publisher doc

    I created a pdf from a Publisher document, and the resolution is less than 300 dpi (about 500KB). The 1/2 page document is over 4MG as a Publisher document, so why did I lose resolution & what can I do to keep the resolution above 300? I tried 3 diff

  • Parsing PHP Vars in AS3

    I'm pulling in vars from a PHP file into AS3, which im very new at, and having a few general and what i assume easy questions: first of all, my php looks like this: <?php $first="VARDATA"; echo "v1=$first"; ?> my question is, why can't i:  echo"$firs