Getting Counts with single query

HI,
I need help in writing a query that gets account counts in a single query,
CREATE TABLE ACCOUNTINFO(     
ACCOUNTID VARCHAR2(20 BYTE) NOT NULL,
ACCOUNTNO VARCHAR2(10 BYTE) NOT NULL,
LAST_DEPOSIT_DATE DATE,
BALANCE NUMBER(10,0));
I have a table like above and I am trying to write a query that gets
Count of accounts with deposits made in last 1 month,
Count of accounts with deposits made in last 2 months
Account Count with balance > 0,
Also, I need to join this ACCOUNTINFO with ACCOUNTMAIN to get name etc details
CREATE TABLE ACCOUNTINFO(     
EMPID VARCHAR2(20 BYTE) NOT NULL,
FNAME VARCHAR2(30 BYTE) NOT NULL,
MNAME VARCHAR2(30 BYTE),
LNAME VARCHAR2(30 BYTE) NOT NULL,
DOB DATE,
ACCOUNTID VARCHAR2(20 BYTE));
Question, how to write a query since I getting too-many counts (I have only 3 in sample above, actual goes on like 3-6, 6-9 etc).

SELECT SUM  (CASE WHEN LAST_DEPOSIT>=ADD_MONTHS(SYSDATE,-1) THEN
               1
             ELSE
               0
             END
            ) COUNT_LAST_MONTH,
       SUM  (CASE WHEN LAST_DEPOSIT>=ADD_MONTHS(SYSDATE,-2) THEN
               1
             ELSE
               0
             END
            ) COUNT_LAST_TWO_MONTHS,
       SUM  (CASE WHEN BALANCE>0 THEN
               1
             ELSE
               0
             END
            ) COUNT_BALANCE_GREATER_ZERO
  FROM ACCOUNTINFO

Similar Messages

  • Getting result with single query

    Hi,
    I'm using db 10.2.0.1.0
    I have a table emp_shift , with data like below
    EmpCode           Shift     Effdate            Default
    1                 SHFT1    02-jan-2012          N
    1                 SHFT2    04-jan-2012          Y
    1                 SHFT3    04-jan-2012          NSo if user inputs EmpCode and Effdate, based on that i've to take the latest record, with default = 'Y' (if any) else default 'N'
    Suppose
    Case 1 : Input Empcode:1 Date:10-jan-2012
    Then i should get the below record
    1                 SHFT2    04-jan-2012          YCase 2 : Input Empcode:1 Date:03-jan-2012
    Then i should get the below record
    1                 SHFT1    02-jan-2012          NI want this result with a single query, is this possible?
    Thanks
    Divya

    Hi Thank you both,
    I'm trying this process through forms. and my forms version is 6i.
    There where i'm trying the query with the cursor, i'm getting error
    Encountered the symbol Order when expecting one of the following
    .()...and my cursor is
    Cursor cur_shft(vemp Varchar2,vdate Varchar2) is Select ESM_SHIFT_TYPE
         from (Select ESM_SHIFT_TYPE from EMPLOYEE_SHIFT_MASTER
                   Where ESM_EMP_CODE = vemp
                   and ESM_EFF_DATE <= vdate
                   Order by ESM_EFF_DATE desc,Esm_Default desc)
                   Where rownum=1 ;Whats wrong?

  • How to get this with Single query

    Friends
    I am sure using SQL analytical function, the following can be achieved using a single query:
    Date_value | Cust_id | Customer_tenue | avg_bal
    01-aug-09 | 111 | 0 | 1000
    01-aug-09 | 112 | 1 | 2000
    01-aug-09 | 113 | 2 | 900
    01-aug-09 | 114 | 3 | 1250
    01-sep-09 | 111 | 1 | 1200
    01-sep-09 | 112 | 2 | 2000
    01-sep-09 | 113 | 3 | 1900
    01-sep-09 | 114 | 4 | 1250
    01-oct-09 | 111 | 2 | 1100
    01-oct-09 | 112 | 3 | 2200
    01-oct-09 | 113 | 4 | 1900Expected result
    If customer’s tenure is 0 then mark as ‘New’,
    If customer’s balance is increased from last month then mark as ‘Augment’
    If customer’s balance is same as last month then mark as ‘Maintain’
    If customer’s balance is decreased from last month then mark as ‘Diminish’
    Else ‘Left’
    Help please....

    If customer’s tenure in last month is 0 then mark as ‘New’,There's not such case in test data... last month is October, isn't it?
    SQL> with t as (select DATE '2009-08-01' Date_value, 111 Cust_id, 0 Customer_tenue, 1000 avg_bal from dual union all
      2  select DATE '2009-08-01', 112 , 1 , 2000 from dual union all
      3  select DATE '2009-08-01', 113 , 2 , 900 from dual union all
      4  select DATE '2009-08-01', 114 , 3 , 1250 from dual union all
      5  select DATE '2009-09-01', 111 , 1 , 1200 from dual union all
      6  select DATE '2009-09-01', 112 , 2 , 2000 from dual union all
      7  select DATE '2009-09-01', 113 , 3 , 1900 from dual union all
      8  select DATE '2009-09-01', 114 , 4 , 1250 from dual union all
      9  select DATE '2009-10-01', 111 , 2 , 1100 from dual union all
    10  select DATE '2009-10-01', 112 , 3 , 2200 from dual union all
    11  select DATE '2009-10-01', 113 , 4 , 1900 from dual)
    12  select date_value, cust_id, avg_bal, oldbal, case when Customer_tenue=0 and nextbal is null then 'NEW'
    13                                                    when oldbal<avg_bal then 'Augment'
    14                                                    when oldbal=avg_bal then 'Maintain'
    15                                                    when oldbal>avg_bal then 'Diminish'
    16                                                    else 'Left' end status
    17    from (select date_value, cust_id, customer_tenue, avg_bal, LEAD(avg_bal) over (partition by cust_id order by date_value desc) oldbal,
    18                 LAG(avg_bal) over (partition by cust_id order by date_value desc) nextbal
    19            from t)
    20  order by cust_id, date_value;
    DATE_VALU    CUST_ID    AVG_BAL     OLDBAL STATUS
    01-AGO-09        111       1000            Left
    01-SET-09        111       1200       1000 Augment
    01-OTT-09        111       1100       1200 Diminish
    01-AGO-09        112       2000            Left
    01-SET-09        112       2000       2000 Maintain
    01-OTT-09        112       2200       2000 Augment
    01-AGO-09        113        900            Left
    01-SET-09        113       1900        900 Augment
    01-OTT-09        113       1900       1900 Maintain
    01-AGO-09        114       1250            Left
    01-SET-09        114       1250       1250 Maintain
    Selezionate 11 righe.Max
    [My Italian Oracle blog|http://oracleitalia.wordpress.com/2009/12/29/estrarre-i-dati-in-formato-xml-da-sql/]

  • Single report with multiple queries OR multiple reports with single query

    Hello Experts,
    I have a confusion regarding Live Office connection for many days. I asked many people but did not get a concrete answer. I am re-posting this question here and expecting an answer this time.
    The product versions that I am using are as follows:
    FrontEnd:
      BOE XI 3.1 SP4 FP 4.1
      Xcelsius Enterprise 2008 SP4
    Backend:
      SAP BW 7.0 EHP1
    I have created a dashboard which is getting data from a webi report using LO connections.
    The webi report has five report parts which are populated by five different queries.
    Now my question is, when the five LO connections are refreshed, is the webi report refreshed five times or just once?
    If the report is refreshed five times, then I guess it is better to have five different webi reports containing single report part, because in that way we can prevent same query being executed multiple times.
    SO what is the best practice- to have a single report having multiple queries - OR - to create multiple webi reports with single query?
    Thanks and Regards,
    PASG

    HI
    I think Best Practice is Multiple reports with single query
    Any way If LO connections refresh 5 time the query will refresh 5 timesRegards
    Venkat

  • INSERTED Table - When it gets populated with single or multiple rows?

    Hi,
    I'm trying to create a trigger which then insert to a table. i'm wondering when does the INSERTED table gets populated with single or multiple rows?
    Should I always assume that the INSERTED Table will contains several rows? What does the scope of the INSERTED table in the trigger, isn't based on the user session?
     The reason why i asked this is because as far as i know inserted table may contain several table when the trigger fires which is why I use cursor to insert  records in the table ( there's a behind why i use cursor).
    But if the inserted table will only contain a single record during the session of the trigger then i can avoid the cursor.
    Thanks.

    But since we control the transaction process and we know for a fact that user will only be able to save a record one at a time, do we still expect multiple rows? I just want to have a clear concept on the INSERTED table.
    ...and then the DBA or someone else sees fit to enter a number of rows directly from a query window. And don't laugh. That is bound to happen sooner or later.
    However, just because this can (and will) happen does not mean that you need to handle it on equal footing with the normal case user entering data through the application. What you cannot permit yourself to is to drop the DBA case on the floor, that is write
    the trigger as if there would either be single-row inserts and produce incorrect results for multi-row inserts.
    But, yes, allowing yourself to use a cursor, if you want to reuse the existing stored procedure is feasible. That is also the more drastic solution suggested by Tom to add an explicit check that disallows multi-row inserts.
    Finally, permit me to comment on this:
    Additionally, it's  difficult to use the code below as i need to pass the identity id of tbl_A to tbl_B
    You can use the OUTPUT clause to capture the values, but that requires that you have something you can map the identity values to in the columns you insert, and this is not always the case. However, there is a lot simpler solution to the problem: don't
    use IDENTITY. IDENTITY is one of these over-used and over-abused features in SQL Server. You need it when you want to support high-concurrency inserts, because rolling your own requires a serialisation point. But with a moderate insertion frequency, IDENTITY
    only gives you headache.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Count(*) with nested query

    Hi,
    I have a question about the count(*) with nested query.
    I have a table T1 with these columns:
    C1 number
    C2 number
    C3 number
    C4 number
    C5 number
    (The type of each column is not relevant for the example.)
    This query:
    select C1, C2, C3, C4
    from T1
    group by C1, C2
    it's not correct becausa C3 and C4 are not columns specified in the GROUP BY expression.
    If if run this query:
    select count(*)
    from (select C1, C2, C3, C4
    from T1
    group by C1, C2)
    I haven't an error message (the result is correctly the number of records).
    Why?
    Thanks.
    Best regards,
    Luca

    Because you are just selecting count(*) and none of the columns from the subquery, Oracle is optimising it by ignoring the selected columns and just running the sub query with the group by columns. I know it seems odd, but if you take a basic example:
    SQL> ed
    Wrote file afiedt.buf
      1  select count(*)
      2  from (select empno, sal, mgr, deptno
      3  from emp
      4* group by deptno)
    SQL> /
      COUNT(*)
             3... all columns but deptno are ignored
    ... but if you include one of the other columns, even if you group by that column...
    SQL> ed
    Wrote file afiedt.buf
      1  select count(*), empno
      2  from (select empno, sal, mgr, deptno
      3  from emp
      4  group by deptno)
      5* group by empno
    SQL> /
    group by empno
    ERROR at line 5:
    ORA-00979: not a GROUP BY expression
    SQL>... the error returns, because you're forcing oracle to include the column in the subquery.

  • Files get open with single click sometimes

    I recently started having this problem. When I browse through different image/video files, some of the files get open with one click only. This is really very annoying. I am event thinking to migrate back to Windows because of this problem.
    How to reproduce the issue:
    -> Open a folder that contains many images/video files
    -> Click on anyone of them to select it
    -> Now click outside the window. So, the finder goes out of the focus (but should stay visible)
    -> Now, inside finder click any other image/video just once, it will open up automatically with just single click

    If you have access to a mouse, try using it. If everything is okay using the mouse, then it is likely trackpad related. Other troubleshooting.
    Try setting up another admin user account to see if the same problem continues. If Back-to-My Mac is selected in System Preferences, the Guest account will not work. The intent is to see if it is specific to one account or a system wide problem. This account can be deleted later.
    Isolating an issue by using another user account
    If the problem is still there, try booting into the Safe Mode.  Shut down the computer and then power it back up. Immediately after hearing the startup chime, hold down the shift key and continue to hold it until the gray Apple icon and a progress bar appear. The boot up is significantly slower than normal. This will reset some caches, forces a directory check, and disables all startup and login items, among other things. If the system operates normally, there may be 3rd party applications which are causing a problem. Try deleting/disabling the third party applications after a restart by using the application unistaller. For each disable/delete, you will need to restart if you don't do them all at once.
    Safe Mode
    Safe Mode - About
    General information.
    Isolating issues in Mac OS X
    Troubleshooting Permission Issues
    Step by Step to Fix Your Mac

  • Update several rows with single query (easy question, I guess)

    Hi all!
    I have table with two columns - name and value.
    I populate it with several sql queries:
    insert into settings (name, value) values ('company_name', 'My Company');
    insert into settings (name, value) values ('company_address', 'Company Address 12');
    insert into settings (name, value) values ('company_city', 'South Park');
    How can update rows with company_name and company_city in single query?
    Thank you in advance!

    How can update rows with company_name and company_city in single query?I guess something like this was meant:
    update settings set value = ??? where name in ('company_name ', 'company_city');But it's still unclear to me what should be used instead of question marks... :)
    Regards.

  • GET Method with long query string

    Hi there,
    Not sure if this has already been answered. Sorry if it has!
    I have a Biztalk application which does a pass-through for all http requests. It is using WCF-WebHttp transport type with URL mapping of /*.
    It works fine except for GET method that has query string longer than 256 characters. It chokes with following exception:
    The adapter "WCF-WebHttp" raised an error message. Details "System.ArgumentOutOfRangeException: The value of promoted property cannot exceed 256 characters. Property "To" Namespace "http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties".
    My question is is there a workaround for this e.g. extend the string length limit? 

    Hi Karsten,
    Try giving the one part of URL in address box and other pass the arguments inside HTTP Method and URL Mapping dialog.
    Eg:
    Address (URI) : https://btstecheddemostorage.blob.core.windows.net
    <BtsHttpUrlMapping>
    <Operation Name="ListFiles"
    Method="GET" Url="/{mycontainer}?restype=container&amp;comp=list"
    /> </BtsHttpUrlMapping>
    Thank YOu,
    Tamil

  • How can I get record count with a query?

    In Client/Server pplication,the client send a query to server.
    How can server get record count by oracle call interface?
    Is it need execute "select count(*) from ...."?

    Yes.
    Either that or increment a counter for each record fetched and
    loop round until you hit the last record.
    The first method would be more efficient on large datasets.

  • How to get count(*) in ABAP Query...

    Hi All,
    Can someone of you tell me, how to do the following in the ABAP Query. I want to get the count of records retreived during the query execution and display it in the output.
    example:::   Select count(*) from VBRK.
    Thanks a lot.
    Thanks!
    Puneet.

    From help doc:
    Note
    The SELECT COUNT( * ) FROM ... statement returns a result table containing a single line with the result 0 if there are no records in the database table that meet the selection criteria. In an exception to the above rule, SY-SUBRC is set to 4 in this case, and SY-DBCNT to zero.
    You can just run SELECT COUNT (*) FROM TABLE
    Number of rows is returned in SY-DBCNT
    Edited by: Kevin Lin on Jul 2, 2008 10:55 PM

  • Fetch data from 50  tables with single query

    Hi,
    I am having a requirement where I should fetch the records count  in a table, since there are close to 50 tables I have written below code, which is working fine with out WHERE  clause, but going to short dump if I use a where clause.
    IF NOT p_sel_opt IS INITIAL.
        LOOP AT p_sel_opt INTO wa_sel_opt .
          ASSIGN wa_sel_opt-low TO <fval>.
          ASSIGN  p_fieldname TO <field>.
          IF <field> IS ASSIGNED AND <fval> IS ASSIGNED.
            SELECT COUNT(*)  FROM (p_tabname) WHERE <FIELD>  = <fval>  .
            IF sy-subrc = 0.
              wa_fi_bukrs-bukrs = <fval>.
              wa_fi_bukrs-table =  p_tabname.
              wa_fi_bukrs-count = sy-dbcnt.
              APPEND wa_fi_bukrs TO it_fi_bukrs.
              CLEAR wa_fi_bukrs.
            ENDIF.
          ENDIF.
        ENDLOOP.
      ENDIF.
    Reason it is giving is
    <field>
    is not availble in the data base tables . what can I do to the above query for that to work.
    Thanks,
    Varun

    replace <field> with (<field>) ok?
    but, its better if you construct your where clause.. i dont know the above will work or not.
    like
    concatenate <FIELD>  ' = ' <fval> into s1 separated by space.
    and pass where (s1).
    check the FM RFC_READ_TABLE. you will get a proper picture
    Edited by: Soumyaprakash Mishra on Dec 13, 2011 11:02 PM

  • Get count with Scope to show only once against rows

    Hi I Have a matrix table with month on the rows and Year on the Columns
    The expression I am using for the data is
    =Count(Fields!data.Value,"Year")
    This shows like this
    2011_H1
    Month 1 256
    Month 2 256
    Month 3 256
    Month 4 256
    Month 5 256
    Month 6 256
    I only want to show the data value once so it looks like this
    2011_H1
    Month 1 256
    Month 2
    Month 3
    Month 4
    Month 5
    Month 6
    I have tried using in the text box visibilty
    =Iif(Previous(ReportItems!data.Value)=ReportItems!data.Value, true, false)
    But I get an error message about aggregate functions can only be used on report items
    How can achieve this?
    Regards

    Hi aivoryuk,
    Just as you said, the previous aggregate function couldn’t be used in a tablix cell in Reporting Services. After testing the issue in my local environment, we can refer to the following methods to work around the issue.
    Method1: Use RowNumber function to control the textbox visibility to only show the last value in the Year column.
    Right-click the cell which contains the expression “=Count(Fields!data.Value,"Year")” to open the Text Box Properties dialog box.
    Select Visibility tab, use the expression below to control the visibility:
    =iif(RowNumber("Year")=reportitems!Year.Value,false,true)
    The following screenshot is for your reference:
    Method2: Use custom code to get the previous value.
    Copy the custom code below and paste it to your report. (Right-click report>Report Properties>Code)
    Public Shared previous as string
    Public Shared current as string
    Public Shared Function GetCurrent(Item as string) as string
    previous=current
    current=Item
    return current
    End Function
    Public Shared Function GetPrevious()
    return previous
    End Function
    Replace the original expression
    =Count(Fields!data.Value,"Year")
    with
    =Code.GetCurrent(count(fields!data.Value,"Year"))
    Use the following expression to control the visibility of the textbox:
    =iif(Code.GetCurrent(count(fields!data.Value,"Year"))=Code.GetPrevious(),true,false)
    The following screenshot is for your reference:
    If you have any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support
    Hi Katherine
    I tried Both solutions and neither worked for me.
    Solution 1 showed no values
    And Solution 2 all values were still present.
    Do you have any suggestions?

  • SQL  statement - Get records with single customerid

    Hi,
    I have this SQL statement as follows:
    SELECT debit_balance,credit_balance,customer_id
    FROM table_balance
    WHERE customer_id IN (SELECT  customer_id
                                          FROM table_balance
                                          GROUP BY customer_id HAVING COUNT (customer_id)= 1)
    {code}_Data:_
    {code:java}
    debit_balance:    credit_balance:   customer_id:
          50                40               1
          10                 0               1
          20                 1               2
           0                 2               3
         121                234              3
    {code}_Expected results:_
    {code:java}
    debit_balance:    credit_balance:   customer_id:
          20                1                2
    {code}From my SQL statement, I think my code is not that efficient. How do I make it even more efficient?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Use analytics
    SQL> with t as
      2  (
      3     select 50 a, 40 b,1 c from dual
      4     union all
      5     select 10, 0, 1 from dual
      6     union all
      7     select 20, 1, 2 from dual
      8     union all
      9     select 0,  2, 3 from dual
    10     union all
    11     select 121,234,3 from dual
    12  )
    13  select a,b,c
    14    from (
    15  select count(c) over(partition by c order by c) cnt, t.*
    16    from t)
    17   where cnt = 1
    18  /
             A          B          C
            20          1          2

  • Single Query with multiple fiscal variants / fiscal period

    Experts,
    Currently we have two different queries 1) for US and 2) for Mexico.
    Both the queries are hard-coded with respective company codes and different fiscal variants. We have i step =1 variable, so in both query we have respective fiscal period by default in variable screen.  The user can decide to run the query for current fiscal period or manually overwrite it for past few fiscal periods.
    Now, we want to consolidate two queries into a single one and behind the scene depending on company code entered by user we want the query to run for default period AND we also want user to have liberty to change it for different fiscal periods (similar to istep 1 variable) which is hard coded for each query. Please advice how to proceed?
    Thanks!

    Hi Durgesh,
    I agree with part 1- we can let user select his company code, but my challenge is pre-populate or get the default fiscal period for different company codes.
    2) You can keep rest of the things as it is, because you will be populating the default period value and if user want he can select the required value manually.
    (Alok) =  So if user runs report in Nov'2011 = the US fiscal period is 002/2012; but for Mexico it might be 011/2011 - so is there any way where we can give this value in prompt screen and at the same time not let user remember these values...
    Since with single query and without hardcoding how to determine the current fiscal period for different company codes?

Maybe you are looking for

  • Adobe PDF Printer (Acrobat Pro 9.3.2) causes Print Spooler crash on Windows 7 64-bit

    We have recently upgraded our office to Windows 7 64-bit. This upgrade has been very smooth with the exception of Adobe Acrobat 9 Pro. We are running Acrobat 9.3.2, I know there are a couple of additional updates available but they do not fix this is

  • Putting apps database in Read-Only mode

    Hi, I want to put the apps database in read-only mode to that user will be able to login into the applications and see data but will not be able to update it. What is the best way to do this? Thanks

  • Optimizing Performance

    I am having a problem with my program as I am not getting the desired frame rate due to all the code that is getting executed per tick. So I have some questions about director and lingo as to which way actually executes faster. 1. Multiple ExitFrame

  • T.Code for Configuration Menu "Funds Management Government"

    Hello, Do we have a T.Code for SPRO node "Funds Management Government". I found T.Code TCMN for Easy access menu but not for FM Config items. Thanks, Ankish

  • Best way to import CC2014 into CC?

    So the apparent known playback problems with the CC2014 version of Premiere has essentially rendered it a complete waste of software, so what's the easiest way to get my projects back into CC? I know I can't just open the file in an earlier version,