Advice with a query to find Accounts with activities within a given period ONLY

Hello there,
I am relatively new to Microsoft T-SQL and I was wondering if someone could help shed some light into a requirement I got...
I have two tables in a database. One with accounts, and another with activities for such accounts. He is a simple diagram:
*NOTE: Dates are in the DD/MM/YYYY format.
Here is what I need to do:
I need to get a list of all the accounts where the LAST activity was created in a date range, along with a count of activities that fall in such range. The idea behind this is to find out accounts with no activity after a certain period.
I can certainly accounts with activities in a given range -- but that does not mean that there was no activities after the range.
For example, if I look for Accounts with activities between Feb/2014 and Mar/2014, this query should NOT return the Contoso account, because it ha an activity after Mar/2014 (i.e.: Meeting with John on 15/Apr/14).
Another example: If I query accounts with activities from 01/Jan/2014 and 03/Apr/2014, it should ONLY return the Adventureworks account:
Adventureworks (3)
[the number in parenthesis is the count of activities in that given time]
This is because all other accounts had activities after 03/Apr/2014.
Could someone please advise the best way to construct this query?
Thanks in advance for the help!
Regards,
P.

SELECT * FROM tbl WHERE CreatiinDate BETWEEN @firstactivities AND  lastactivites
AND NOT EXISTS 
(SELECT * FROM tbl t WHERE CreatiinDate>=@lastactivites
AND
tbl.AccountID=T.AccountID )
OR
SELECT * FROM tbl WHERE
AccountID  NOT IN (SELECT
AccountID FROM
tbl t WHERE CreatiinDate>@lastactivites) 
AND CreationDate BETWEEN
@firstactivities AND  lastactivites
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

Similar Messages

  • Query to find records with more than 2 decimal places

    I have written the below query to find records with more than 2 decimal places, but it is returning records with decimal places 1 & 2.
    The datatype of the AMT column is NUMBER (without any precision).
    SELECT amt  FROM amount_table
    WHERE substr(amt, instr(amt, '.')) LIKE '.%'
           AND length(substr(amt, instr(amt, '.') + 1)) > 2Output:-
    AMT
    *41591.1*
    *275684.82*
    *64491.59*
    *3320.01*
    *6273.68*
    *27814.18*
    *30326.79*
    131.8413635
    162.5352898
    208.5203816
    8863.314632
    22551.27856
    74.716992
    890.0158441
    2622.299682
    831.6683841
    *1743.14*
    2328.195877
    3132.453438
    5159.827334
    3.236234727
    37.784
    Thanks

    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    create table amount_table
      LINE_NUMBER        NUMBER not null,
      FEE_AMT            NUMBER not null
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (60208, 41591.1);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (60213, 275684.82);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (60238, 64491.59);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (63026, 3320.01);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (59906, 6273.68);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (83111, 27814.18);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (83114, 30326.79);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112395, 131.8413634682);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112399, 162.5352898104);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112402, 208.5203815738);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112403, 8863.3146321954);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112406, 22551.2785551322);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112407, 74.716992);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112410, 890.015844079);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112411, 2622.2996817048);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112414, 831.6683840698);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112415, 1743.14);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112418, 2328.1958771886);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112419, 3132.4534379886);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112422, 5159.8273341686);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112423, 3.2362347266);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112426, 37.784);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112427, 198.7423503696);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112430, 0.7220848332);
    insert into amount_table (LINE_NUMBER, FEE_AMT)
    values (2112433, 12.4149375254);

  • When opening my Outlook 2010 with new added e-mail account with Exchange Server, I have to click manually on my standard e-mail account for checking mail

    When opening my Outlook 2010 with new added e-mail account with Exchange Server supplied by my employer, I have to click manually on my standard e-mail account for checking mail. Do I have to upgrade my Microsoft Office 2010 or how can I make my Outlook
    2010 check all my four e-mail accounts without manually click on my accounts?
    Sincerely
    Ketil Hothorp

    Hello Ketil,
    Good Day...
    Seems to be the Issue is Syncing emails, now I would recommend you to Remove and Add the Account and try and check if the emails are getting synced automatically.
    Hope this is with Single User. If it is with Multiple Users then we need to check the permissions assigned.
    Regards,
    Praveen

  • Query to find out the Activities done against a table

    Hi,
    One table has been truncated and data reloaded into the table by the user. But at latter stage user deny that activity. I believe all these activities stored in any oracle 10g database table.
    Need a query to find out the activities done on a specific date say 6th Sep.
    This is too urgent. Thanks in advance

    Hi,
    Welcome to the forum!
    If you don't have enable table auditing maybe you can see last_ddl_time column of user_objects view:
    Connected to Oracle Database 10g Express Edition Release 10.2.0.1.0
    Connected as hr
    SQL> select * from test2;
          COL1       COL2       COL3
             1          1          3
             1          2          3
             1          3          3
    SQL> select to_char(uo.created, 'DD/MM/YYYY HH24:MI:SS'), to_char(uo.last_ddl_time, 'DD/MM/YYYY HH24:MI:SS') from user_objects uo where uo.object_name = 'TEST2';
    TO_CHAR(UO.CREATED,'DD/MM/YYYY TO_CHAR(UO.LAST_DDL_TIME,'DD/M
    12/09/2009 12:20:26            12/09/2009 12:20:27
    SQL> truncate table test2;
    Table truncated
    SQL> select to_char(uo.created, 'DD/MM/YYYY HH24:MI:SS'), to_char(uo.last_ddl_time, 'DD/MM/YYYY HH24:MI:SS') from user_objects uo where uo.object_name = 'TEST2';
    TO_CHAR(UO.CREATED,'DD/MM/YYYY TO_CHAR(UO.LAST_DDL_TIME,'DD/M
    12/09/2009 12:20:26            12/09/2009 14:01:21
    SQL> Regards,

  • Writing a query to find out who is having a given responsibility name.

    Hi,
    I am new to Oracle Apps and have no idea about its tables. Can anyone please help me in writing a query to find out who is having a given responsibility name.
    Thanks in advance.
    Regards
    Himanshu

    Hi
    you can get required data by using this query
    select usr.user_name
    ,     res.responsibility_name
    from fnd_user usr
    ,     FND_USER_RESP_GROUPS_DIRECT usrrep
    ,     fnd_responsibility_tl res
    where usr.user_id=usrrep.user_id
    and usrrep.responsibility_id=res.RESPONSIBILITY_ID
    group by usr.user_name,res.responsibility_name
    Regards,
    Venky

  • Should I switch from shared iCloud account with wife to two separate accounts with family sharing?

    My wife and I have always shared 1 iCloud accpunt between our our 5s phones, iPad, and an old 4s which is now just a toy for our toddler. With ios 8 I am not sure if it is possible or practical any more. We do it to share purchases and the photo stream and a Google calendar.
    With ios 8, it seems to be impossible for both of our phones to share their location. From what I can tell, only 1 device at a time on the icloud account can share its location. Is that a correct assumption? And icloud no longer gives the option for each of us to sign into separate itunes accounts on find my friends. We are forced to sign in with our 1 shared iCloud account. So we can no longer use find my friends to see each other's location.
    So has ios8 rending sharing an iCloud account useless? I'm wondering if we now need to have separate accounts and link them with family sharing. Will we lose the benefits of having our 1 shared account? I just wanted to make sure we wouldn't lose anything if I set her up with a new account and linked it with family sharing.

    I have lots of questions about this and other things too; I have been sharing my account with my wife and daughter for years through 10s of iPhones and iPads and with the introduction of IOS8 we are having lots of new and not so fun problems.
    As to your question about location.  I have three iPhones and one iPad using the same account now (on IOS 8) and all four devices show up with Find my iPhone.  My wife's was not showing up today but I went in and turned on the new feature "Send last Location" and all of a sudden her phone was able to be found again.  Not sure if that will solve your problem but just wanted you to know that I have the four devices all showing up in Find my iPhone with a shared account.

  • Query to Find Account Balances (Actual & Budgeted).

    Hi
    can any one suggest a query to list all GL (R12) Account (Segment2) Balances (Actual and Budgeted) for a given Enitity (Segment1) and Period.
    Some accounts have sub-accounts with Parent child relationship. List should include all child accounts where ever balances exist.
    or Pl. point me thread if it is already answered earlier in this forum.
    Thanks,
    T.
    Edited by: user13072694 on May 28, 2010 2:15 PM
    Edited by: user13072694 on May 28, 2010 2:19 PM
    Edited by: user13072694 on May 28, 2010 2:25 PM

    Hello.
    See if this query helps you:
    SELECT cc.segment2,
    nvl(sum(bal.begin_balance_dr + bal.period_net_dr - bal.begin_balance_cr - bal.period_net_cr),0) "Actual Balance",
    nvl(sum(balb.begin_balance_dr + balb.period_net_dr - balb.begin_balance_cr - balb.period_net_cr),0) "Budget Balance"
    FROM gl_balances bal, gl_balances balb, gl_code_combinations cc
    WHERE cc.code_combination_id = bal.code_combination_id
    AND balb.code_combination_id = cc.code_combination_id
    AND bal.set_of_books_id = <'your SOB id'>
    AND balb.set_of_books_id = <'your SOB id'>
    AND bal.period_name = <'your actual period name'>
    AND balb.period_name = <'your budget period_name'>
    AND bal.actual_flag = 'A'
    AND balb.actual_flag = 'B'
    AND bal.currency_code = <'you SOB currency code'>
    AND balb.currency_code = <'your SOB currency code'>
    GROUP by cc.segment2
    Hope this helps,
    Octavio

  • Backend query to find metrics with thresholds

    Hi,
    Is there a way to query the backend tables in repository database to find the metrics with thresholds on a database.I want to findout the missing warning/critical thresholds for all the targets.Any inputs for this may be helpful to me.
    Thanks.

    You might want to create a User Deinfed Metric that does a query on the SYSMAN schema to find out.
    Checkout
    Oracle® Enterprise Manager Extensibility Guide
    10g Release 5 (10.2.0.5)
    http://download.oracle.com/docs/cd/B16240_01/doc/em.102/b40007/toc.htm
    For description of all SYSMAN views to select your data
    Regards
    Rob
    http://oemgc.wordpress.com

  • Query Data Finder Server with ActiveX

    I haven't been able to find much resources on how to use ActiveX to Query a Data Finder Server.  I know that this is all supposed to be done with the ToCommand but I have no idea how it is done beyond this.  Can someone give me some direction as to what commands are needed to Open a Data Finder, Create a Query, Merge Queries, and get resulting file paths?
    Thanks,
    David Vanleeuwen

    Hi Djvanlee,
    So they are not ActiveX commands, you would use VBScript Commands with a ToCommand reference writing to DIAdem through invoke nodes.  Are you using LabVIEW with the ToCommand reference?  
    An example of this can be found by opening up the DIAdem - Example Finder by going to Help>>Examples and it will be on the Context tab under the directory Examples>>Create Scripts>>Using Interfaces>>Controlling DIAdem from LabVIEW.  Then the commands can be found in the DIAdem Help on the Contents tab by going to Programming Reference>>Object Oriented Script Interfaces>>DIAdem NAVIGATOR>>Methods.  The methods you would reference are labeled as <DataFinder>.  It looks like the main commands you would need are:
    ConnectDataFinder()
    CreateQuery()
    Load Query()
    SaveQuery()  \\Note when you save the query you will have to indicate the path.
    If you are looking for a good example of programmatically using the DataFinder in the script tab in DIAdem you can find this in the ExampleFinder on the Contents tab at "Extending Functionalities with Scripts>>Context Menu for the Search Results of the DataFinder".  The ResultsList_Menus_Add.VBS connects to the DataFinder programmatically and loads a query.
    Peter T
    Applications Engineer
    National Instruments

  • Query to find tables with excessive initial extent settings

    After loading a database dump we found many tables occupying large space due to large initial extents storage parameter but with very few rows and am trying to determine if it would be worth the effort to reorganize the entire schema. In other words, we are looking for a query to compare the estimated actual space that would be occupied by the table rows vs. the current size to see the space savings if we were to reorganize.
    I hacked out a script to calculate the estimated size using the table stats (or 64K if estimate is lower) and compared that vs. the extents allocated to each table but this seems a rather inexact way of doing it. Is there a more accurate approach?
    Doing this on Oracle database 10.2.0.4 on Windows Server 2003 SE
    SELECT a.table_name,
               b.table_size_MB,
               ROUND((a.num_rows * a.avg_row_len) / (1024 * 1024),2) calc_size_MB, 
               b.table_size_MB - GREATEST(ROUND((a.num_rows * a.avg_row_len) / (1024 * 1024),2), 0.0625) savings_MB
      FROM dba_tables a,
          (SELECT segment_name, sum(bytes)/(1024*1024) table_size_MB
             FROM dba_extents
            WHERE tablespace_name like 'PMDX' and segment_type = 'TABLE'
            GROUP BY segment_name) b
    WHERE a.owner = 'CAS' and a.table_name = b.segment_name
    ORDER BY b.table_size_MB desc
    TABLE_NAME                     TABLE_SIZE_MB CALC_SIZE_MB SAVINGS_MB
    TPM06_POL_DATA_WRK_PREV                  640       493.46     146.54
    TPM06_POL_DATA_WRK_CURR                  640       496.57     143.43
    TPM06_POL_DATA_201006                    640        496.8      143.2
    TPM06_POL_DATA_201005                    640       494.87     145.13
    TPM06_POL_DATA_201004                    640       490.45     149.55
    TPM07_MOV_DTLS_WRK                       256       198.66      57.34
    ...

    Hi,
    Didn't you check the dba_extents view with respect to the tables which you estimated.
    After loading a database dump we found many tables occupying large space due to large initial extents storage parameterYou might have modified the initial extent size before to your load by pre-created tables ,which might helped out with current situation prior to this as you might be well known with your current database. Does the segement using Autoallocate or Uniform. What is the block size of DB.
    - Pavan Kumar N

  • Query to find numbers with dashes

    Help. I want to write a query that will return all the numbers in my table that have dashes (-) in positions 5, 8 and 12. I tried using the INSTR function, with the positions, but do not get the desired result.
    All suggestions are welcome!

    SQL> create table y as select '1234-67-901-34' y from dual;
    Table created.
    SQL> select to_number(x) from (select replace(y,'-') x from y where substr(y,5,1)='-' and substr(y,8,1)='-' and substr(y,12,1)='-')
    TO_NUMBER(X)
    12346790134

  • SCCM 2012 Query to find units with IPv6 Enabled?

    We've found a need to locate computers that may have IPv6 enabled for audit purposes, and then we'll disable them at a later date.
    Has anyone been able to create a successful query in SCCM 2012 to get that information? 
    I found this but it spit back the IPv4 info for all the units in our device collection, plus it's for SCCM 2007. http://www.myitforum.com/forums/Query-for-systems-with-IPv6-enabled-m227020.aspx
    Appreciate any input, thanks!
    This topic first appeared in the Spiceworks Community

    If you're using % in the value field the operator must be "Like" . In your case, the query should look like
    select SMS_R_USER.ResourceID,SMS_R_USER.ResourceType,SMS_R_USER.Name,SMS_R_USER.UniqueUserName,SMS_R_USER.WindowsNTDomain from SMS_R_User where SMS_R_User.UserPrincipalName Like
    "TQA%" order by SMS_R_User.UserPrincipalName
    Kindly mark as answer/Vote as helpful if a reply from anybody helped you in this forum. Delphin

  • Query to find SQL with changed plans

    I am trying to find out which SQL statements have changed plans since they were first executed.
    I'm trying to run this on all databases from 9i upwards and I am assuming that I have no licensed access to the AWR. However, Statspack is installed on all databases. (So querying things like STATS$SQL_PLAN is fine).
    I am having difficulty understanding what HASH_VALUE, OLD_HASH_VALUE and PLAN_HASH_VALUE are, and how they can be used to help answer the problem. I am also trying not to use SQL_ID, since that column isn't there in 9i (I think), and I'd like something that is generically usable from 9i to 11g, if at all possible.
    Any hints, please.
    Edited by: Catfive Lander on May 14, 2012 12:01 AM

    Hi Sakshi,
    Try out this query if it can help you !
    SELECT a.user_name, a.description, c.responsibility_name, c.creation_date as ASSIGNED_DATE>FROM apps.fnd_user a,
    >apps.fnd_user_resp_groups b,
    >apps.fnd_responsibility_vl c
    >WHERE a.user_id = b.user_id
    >AND b.responsibility_id = c.responsibility_id
    >AND a.creation_date < = '01-JUN-07'
    ORDER BY a.user_name;Thanks,
    Anchorage :)

  • Query report for account with the check no.

    Hi,
    I need a report where it should have the posting date,duedate,check no.,row details which is available in JDT1,Debit amt,balance  of a g/l account.
    I couldn't retrive the check no. for that account..
    Kindly help me.

    Ref3 is field in journal entry where cheque no is captured.
    Jeyakanthan

  • SQL Query - To Find Users with end dated responsibilities

    Oracle Apps ver: 11.5.10.2
    Oracle DB - 9i
    How can i list users and the access assigned to them for a specific division irrespective of the responsibility being end dated at responsibility level

    Hi Sakshi,
    Try out this query if it can help you !
    SELECT a.user_name, a.description, c.responsibility_name, c.creation_date as ASSIGNED_DATE>FROM apps.fnd_user a,
    >apps.fnd_user_resp_groups b,
    >apps.fnd_responsibility_vl c
    >WHERE a.user_id = b.user_id
    >AND b.responsibility_id = c.responsibility_id
    >AND a.creation_date < = '01-JUN-07'
    ORDER BY a.user_name;Thanks,
    Anchorage :)

Maybe you are looking for

  • How can I debug a DLL created with MS Visual Studio C++ using CVI?

    I have developed a DLL using MS Visual Studio C++, which is called by an other application written in CVI. My goal is to debug the DLL written with C++ when is called from CVI. So far I have some msg popups, but I would like to have more debugging ca

  • Add a Document upload button to a form?

    Hello, Does anyone know if I can add a button to a form that will allow the user to upload a document? Might sound crazy but it would be nice. I have a form I created with questions that would be answered in a paragraph form. This in some cases will

  • What happens to CC or Watermarks when imported into PrPro

    HI all, my question (s) are about information that is stored in the out of tv safety feilds when imported into Adobe premeir pro. files will be mpeg-2 video files SD and Hd 1) what happens to closed Captioning data (does it get moved or is it strippe

  • I want to give enable a button for a user and disable for others in tcode

    Hi all , I want to give authorisation based on user for TCODE : CCO02 where i enter Production Order. After clicking enter button in the next screen for the Total order quantity Icon i want to assign Authorisation to enable to one user and to set in

  • Pages doesn't show the preview view of documents

    I don't know if anyone has the same problem, but since the update, my pages for iOS (even in iPhone or iPad), doesn't show the preview view of each document. I have to open a document, close it and then it appears the preview. But if I close the app,