Help in framing SQL Query

Hi,
Could someone please help me with the below requirement.
On the sample EMP table I want a report that is like:
Manager Tot_Joiniees_Q1 Tot_Joiniees_Q2 Tot_Joiniees_Q3 Tot_Joiniees_Q4Please refer the below query for the relevant columns and the quarter definitions:
SELECT   mgr,
         CASE
            WHEN TO_CHAR (hiredate, 'MON') IN ('JUN', 'JUL', 'AUG')
               THEN 'Q1'
            WHEN TO_CHAR (hiredate, 'MON') IN ('SEP', 'OCT', 'NOV')
               THEN 'Q2'
            WHEN TO_CHAR (hiredate, 'MON') IN ('DEC', 'JAN', 'FEB')
               THEN 'Q3'
            WHEN TO_CHAR (hiredate, 'MON') IN ('MAR', 'APR', 'MAY')
               THEN 'Q4'
         END qtd,
         COUNT (DISTINCT ename)
    FROM emp
GROUP BY mgr,
         CASE
            WHEN TO_CHAR (hiredate, 'MON') IN ('JUN', 'JUL', 'AUG')
               THEN 'Q1'
            WHEN TO_CHAR (hiredate, 'MON') IN ('SEP', 'OCT', 'NOV')
               THEN 'Q2'
            WHEN TO_CHAR (hiredate, 'MON') IN ('DEC', 'JAN', 'FEB')
               THEN 'Q3'
            WHEN TO_CHAR (hiredate, 'MON') IN ('MAR', 'APR', 'MAY')
               THEN 'Q4'
         END
ORDER BY 1, 2Thanks,
CJM

SELECT   mgr Manager,
         COUNT(CASE WHEN TO_CHAR(hiredate,'Q') = '1' then 1 end) Tot_Joiniees_Q1,
         COUNT(CASE WHEN TO_CHAR(hiredate,'Q') = '2' then 1 end) Tot_Joiniees_Q2,
         COUNT(CASE WHEN TO_CHAR(hiredate,'Q') = '3' then 1 end) Tot_Joiniees_Q3,
         COUNT(CASE WHEN TO_CHAR(hiredate,'Q') = '4' then 1 end) Tot_Joiniees_Q4
    FROM emp
    GROUP BY mgr,
             TO_CHAR(hiredate,'Q')
   MANAGER TOT_JOINIEES_Q1 TOT_JOINIEES_Q2 TOT_JOINIEES_Q3 TOT_JOINIEES_Q4
      7566               0               0               0               1
      7839               0               3               0               0
      7698               0               0               2               0
      7788               0               1               0               0
      7782               1               0               0               0
      7566               0               1               0               0
      7902               0               0               0               1
      7698               2               0               0               0
                         0               0               0               1
      7698               0               0               0               1
10 rows selected.
SQL> SY.

Similar Messages

  • Help with an SQL Query on the Logger

    We are running UCCE 8.5(3) and need help with an SQL query. When I run the below I would also like to see skill group information(name preferably)? Any help would be greatly appreciated!
    select * from dbo.t_Termination_Call_Detail where DateTime between '10-11-2012 00:00:00:00' and
    '10-11-2012 23:59:59:59'

    David, thanks for replying.  Unfortunitly I don't know enough about SQL to put that into a query and have it return data.  Would you be able to give an example on what the query would look like?

  • Help needed in framing SQL query.

    Hi,
    I have table having following schema:
    PRODUCT_ID         INT
    DATE                   DATETIME
    ITEMS_SOLD         INT
    This table contains data for a week (sunday to saturday). I want to write an SQL query to get (filter out) PRODUCT_ID of products which has same no. of ITEMS_SOLD for all 7 days. Also for given PRODUCT_ID I need to find the longest period of successive days where the no. of ITEMS_SOLD is same for all days in this period. Eg.(PRODUCT_ID 23 was sold as following along the week in no. of units sold: 4,6,6,6,6,7,4 .So the longest period is *4 days* from Monday to Thursday.) The first condition is special case of second condition where no. of days is 7.
    Any help to get the SQL query will be appreciated.
    Thanks,
    Akshay.

    PRODUCT_ID      DATE           ITEMS_SOLD
    1          10/10/2011     3
    1          11/10/2011     3
    1          12/10/2011     3
    1          13/10/2011     3
    1           16/10/2011     5
    2          10/10/2011     4
    2           11/10/2011     4
    2          12/10/2011     4
    2          13/10/2011     4
    2           14/10/2011     4
    2          15/10/2011     4
    2          16/10/2011     4
    Output:
    PRODUCT_ID ITEMS_SOLD NO_OF_DAYS
    1          3                4     
    2          4               7
    Explanation of results:
    The table to be queried contains data for 1 week: from 10/10/2011(Sunday) to 16/10/2011(Saturday). Now, product with PRODUCT_ID '1' was sold on dates 10,11,12,13,16. Out of these 5 days 3 units were sold on 4 successive days (from 10-13). So output should be like :
    PRODUCT_ID ITEMS_SOLD NO_OF_DAYS
    1          3               4     
    as longest period of successive days is 4 where same no. of units were sold i.e 3 units (other period is of 1 day on 16th ).
    For PRODUCT_ID 2 we have only one period of 7 days where 4 units were sold each day. So we output :
    PRODUCT_ID ITEMS_SOLD NO_OF_DAYS
    2           4               7
    Other case where same PRODUCT_ID have different units sold on each day should be ignored.
    I hope that clarifies the problem more. Let me know in case I have missed out anything which should have been mentioned.
    -Akshay.

  • Help with T-SQL query

    I have 3 hierarchical tables. [Parent] ->[Child1]->[Child2]
    I have [Xref] table which stores the documents associated with these three tables. In the [Xref] table, the column “TypeID” defines to which table the document is associated with.
    Below is the table structure with some sample data.
    Question: Given parented I want to get all the documents associated with parent as well its children. My sql query uses Union and its working fine. But Is there any other simple way to re-write this query?
    (Note that this is just an example, the actual hierarchy is pretty long so my SQL is getting little messy and I want simplify it.)
    TYPES
    TypeID TypeName
    1 Parent
    2 Child1
    3 Child2
    TABLE - PARENT
    ParentID
    1
    2
    3
    TABLE - CHILD1
    Child1ID ParentID
    1 1
    2 1
    3 2
    TABLE - CHILD2
    Child2ID Child1ID
    1 1
    2 1
    3 2
    4 2
    XREF
    DocumentID TypeID LocatorID
    1 1 1
    2 1 2
    3 1 3
    4 2 1
    5 2 2
    6 2 3
    7 3 1
    8 3 2
    9 3 3
    10 3 4
    SELECT DocumentID FROM XREF X
    JOIN Parent P ON P.ParentID = x.LocatorID AND TypeID = 1 -- Parent
    WHERE P.ParentID = @ParentID
    UNION
    SELECT DocumentID FROM XREF X
    JOIN Child1 C1 ON C1.Child1ID = x.LocatorID AND TypeID = 2 -- Child1
    JOIN Parent P ON P.ParnetID = C1.ParentID
    WHERE P.ParentID = @ParentID
    UNION
    SELECT DocumentID FROM XREF X
    JOIN Child2 C2 ON C2.Child1ID = x.LocatorID AND TypeID = 3 -- Child2
    JOIN Child1 C1 ON C1.Child1ID = c2.Child1ID
    JOIN Parent P ON P.ParnetID = C1.ParentID
    WHERE P.ParentID = @ParentID

    Can you child span multiple levels? If yes, best way would be to use CTE
    see
    http://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Help with translating SQL query from SQL Server syntax to Oracle syntax

    Hi,
    is it someone that can help me translate following SQL query from SQL Server syntax to Oracle syntax.
    SELECT ID,
    [LMT(MTR)] = MAX(case when TYPE = 'LMT' then VALUE end),
    [AAD(KGM)] = MAX(case when TYPE = 'AAD' then VALUE end),
    [VOL(MTQ)] = MAX(case when TYPE = 'VOL' then VALUE end)
    FROM yourtable
    GROUP BY ID
    Your help is highly appreciated, thanks in advance.

    Like this,
    SELECT ID,
    MAX(case when TYPE = 'LMT' then VALUE end) LMT_MTR,
    MAX(case when TYPE = 'AAD' then VALUE end) AAD_KGM ,
    MAX(case when TYPE = 'VOL' then VALUE end) VOL_MTQ
    FROM yourtable
    GROUP BY ID-Arun

  • Newbie - help with a SQL query for a bar chart  - Originally posted in APEX

    I originally posted this in the APEX forum but someone there suggested this is more of a SQL question.  Anyone out there who can provide some assistance?
    Hi,
    I'm a new user on APEX with no real SQL knowledge and I'm trying to build a dashboard with charts into an existing APEX application. Based on another application, I have come up with the following SQL code:
    select null link
    , CATEGORY label
    , count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
    , count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
    from GRAPO_PROHEADTRK
    where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
    group by CATEGORY
    Order by COUNT(PROJECT_ID) DESC
    The code from the other app was:
    select null link
    , FUNCTIONAL_AREA label
    , count (decode(PROJECT_STATUS,'Active',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'Complete',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'On Hold',PROJECT_ID)) "On Hold"
    , count (decode(PROJECT_STATUS,'Recurring',PROJECT_ID))"Recurring"
    , count (decode(PROJECT_STATUS,'Pipeline',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'Not Approved',PROJECT_ID))"Not Approved"
    from PM_V2
    where LOB='S2S' and (FUNCTIONAL_AREA='Accounts Payable' or FUNCTIONAL_AREA='Expense' or FUNCTIONAL_AREA='Procurement' or FUNCTIONAL_AREA='Fixed Assets')
    group by FUNCTIONAL_AREA
    Order by COUNT(PROJECT_ID) DESC
    I'm getting a "Failed to parse SQL query!" error when I try to run validation.
    Is this enough info for some assistance? Any help would really be appreciated.
    Thanks,
    Rachel

    Hi, Rachel,
    user10774102 wrote:
    I originally posted this in the APEX forum but someone there suggested this is more of a SQL question.  Anyone out there who can provide some assistance?
    Hi,
    I'm a new user on APEX with no real SQL knowledge and I'm trying to build a dashboard with charts into an existing APEX application. Based on another application, I have come up with the following SQL code:
    select null link
    , CATEGORY label
    , count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
    , count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
    from GRAPO_PROHEADTRK
    where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
    group by CATEGORY
    Order by COUNT(PROJECT_ID) DESCIs there a problem with the code above?
    It's curious that the WHERE clause includes "PROJECT_STATUS='6'", but there is no pivoted column for project_status='6', like there is for '1' through '5'. That's not necessarily a mistake, and it wouldn't raise an error in any case.
    Instead of
    where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')you could say
    where PROJECT_STATUS  IN ('1', '2', '3', '4', '5', '6')but that probably has nothing to do with your current problem.
    The code from the other app was:
    select null link
    , FUNCTIONAL_AREA label
    , count (decode(PROJECT_STATUS,'Active',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'Complete',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'On Hold',PROJECT_ID)) "On Hold"
    , count (decode(PROJECT_STATUS,'Recurring',PROJECT_ID))"Recurring"
    , count (decode(PROJECT_STATUS,'Pipeline',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'Not Approved',PROJECT_ID))"Not Approved"
    from PM_V2
    where LOB='S2S' and (FUNCTIONAL_AREA='Accounts Payable' or FUNCTIONAL_AREA='Expense' or FUNCTIONAL_AREA='Procurement' or FUNCTIONAL_AREA='Fixed Assets')
    group by FUNCTIONAL_AREA
    Order by COUNT(PROJECT_ID) DESC
    I'm getting a "Failed to parse SQL query!" error when I try to run validation.Is that an Apex error message? Sorry, I don't know anything about Apex.
    If you can't get a more specific error message from Apex, then try debugging this statement in SQL*Plus. When you get it fixed, then you can copy it back into Apex.
    If this is a SQL problem, then you should be able to re-create the problem in pure SQL.
    If you can't re-create the problem in pure SQL, then it's probably an Apex problem, and belongs in the Apex forum, not here.
    I don't see anything obviously wrong with your code, but I can't tell if, for example, you spelled a column name wrong, or if something has the wrong data type
    Is this enough info for some assistance? Any help would really be appreciated.It wiould be better if you posted a completE script that people could run to re-create the problem, and to test their ideas.
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Always say which version of Oracle (and any other software, such as Apex) you're using.

  • Newbie - need help with a SQL query for a bar chart

    Hi,
    I'm a new user on APEX with no real SQL knowledge and I'm trying to build a dashboard with charts into an existing APEX application. Based on another application, I have come up with the following SQL code:
    select null link
    , CATEGORY label
    , count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
    , count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
    from GRAPO_PROHEADTRK
    where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
    group by CATEGORY
    Order by COUNT(PROJECT_ID) DESC
    The code from the other app was:
    select null link
    , FUNCTIONAL_AREA label
    , count (decode(PROJECT_STATUS,'Active',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'Complete',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'On Hold',PROJECT_ID)) "On Hold"
    , count (decode(PROJECT_STATUS,'Recurring',PROJECT_ID))"Recurring"
    , count (decode(PROJECT_STATUS,'Pipeline',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'Not Approved',PROJECT_ID))"Not Approved"
    from PM_V2
    where LOB='S2S' and (FUNCTIONAL_AREA='Accounts Payable' or FUNCTIONAL_AREA='Expense' or FUNCTIONAL_AREA='Procurement' or FUNCTIONAL_AREA='Fixed Assets')
    group by FUNCTIONAL_AREA
    Order by COUNT(PROJECT_ID) DESC
    I'm getting a "Failed to parse SQL query!" error when I try to run validation.
    Is this enough info for some assistance? Any help would really be appreciated.
    Thanks,
    Rachel

    Hello,
    This is more of an SQL question, rather than specifically APEX-related. It's notable that you say: I'm a new user on APEX with no real SQL knowledgeWhich is fine (we all have to start somewhere, afterall) but it might be worth de-coupling the problem from APEX in the first instance. I'd also strongly recommend either taking a course, reading a book (e.g. http://books.google.co.uk/books?id=r5vbGgz7TFsC&printsec=frontcover&dq=Mastering+Oracle+SQL&hl=en#v=onepage&q=Mastering%20Oracle%20SQL&f=false) or looking for a basic SQL tutorial - it will save you a whole lot of heartache, I promise you. Search the oracle forums for the terms "Basic SQL Tutorial" and you should come up with a bunch of results.
    Given that you've copied your query template from another, I would suggest ensuring that the actual query works first of all. Try running it in either:
    * SQL Editor
    * SQL*Plus
    * an IDE like SQL Developer (available free from the OTN: http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html ) or TOAD or similar.
    You may find there are syntax errors associated with the query - it's difficult to tell without looking at your data model.
    select null link
    , CATEGORY label
    , count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
    , count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
    from GRAPO_PROHEADTRK
    where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
    group by CATEGORYNote that your "order by" clause references a field called "PROJECT_ID", which exists in the old query but you've changed other similar references to "PROJECT_STATUS" - is it possible you've just missed this one? The perils of copy-paste coding I'm afraid...

  • Selection screen - search help with dynamic sql query

    hey ,
    is it possible to change the search help of the selection field ?
    when i create the range table i put a data element :
    create a range table that consists of this new data element
      LT_RANGE_TABLE = WD_THIS->M_HANDLER->CREATE_RANGE_TABLE( I_TYPENAME = 'S_CARR_ID' ).
    can i control the search help via the the data element or by other methods ?
    i want that when the user press F4 the values that will show is the result of a sql query that i will write .
    is it possible ?
    thanks
    ASA.

    Hi,
    yes it is possible...
    This is my test code for say personal number select options...
    lt_range_table = wd_this->m_handler->create_range_table(
      i_typename = 'PERSNO' ).
    add a new field to the selection
      wd_this->m_handler->add_selection_field(
      i_id = 'PERSNO'
    I_VALUE_HELP_TYPE = if_wd_value_help_handler=>CO_PREFIX_SEARCHHELP
    I_VALUE_HELP_ID = 'ZHELP_WDA_PERNR'   "this is the custom search help we need to create
    I_NO_INTERVALS = abap_true
      it_result = lt_range_table
      i_read_only = read_only ).
    do the following:
    1) copy the std function module: F4IF_SHLP_EXIT....to ZF4IF_SHLP_EXIT_pernr (in my case i am testing for pernr so my fm
    name is like that....obviously it can be anything you want...under the recommended naming convention)
    2) look for "STEP SELECT"
    STEP SELECT    (Select values)
    3)write the code as follows:
    "NOTE: this is my testing code...but you can build your logic on it....
    IF CALLCONTROL-STEP = 'SELECT'.
    types: begin of zpri_listing,
    pernr type PERSNO,
    end of zfund_listing.
    DATA: lo_syuname TYPE sy-uname.
    data itab type standard table of Zpri_LISTING.
    data wa type zpri_listing.
        DATA : t_fields LIKE TABLE OF shlp_tab-fielddescr.
        DATA : w_fields LIKE LINE OF shlp_tab-fielddescr.
        DATA : l_fname TYPE dfies-lfieldname.
        IF lo_syuname <> sy-uname.  "means we were here before and ITAB is filled...fm retains its data values...unless refresh happens
    "this if condition make sure that we do not do this select all the time as long as the same user is logged in...
    "a user can press f4 many times...you might want to enhance this logic a little bit more for performance
          lo_syuname = sy-uname.
    ))))))))))))))HERE DO YOUR SELECT(((((((((((((((((((((
    select pernr from "sometable" into table itab.
        ENDIF.
        LOOP AT shlp_tab.
          LOOP AT shlp_tab-fielddescr INTO w_fields.
            l_fname = w_fields-fieldname.
            CALL FUNCTION 'F4UT_PARAMETER_RESULTS_PUT'
              EXPORTING
                parameter               = w_fields-fieldname
              OFF_SOURCE              = 0
              LEN_SOURCE              = 0
              VALUE                   =
               fieldname               = l_fname
              TABLES
                shlp_tab                = shlp_tab
                record_tab              = record_tab
                source_tab              =  itab
              CHANGING
                shlp                    = shlp
                callcontrol             = callcontrol
             EXCEPTIONS
               parameter_unknown       = 1
               OTHERS                  = 2
          ENDLOOP.
        ENDLOOP.
        IF sy-subrc EQ 0.
          callcontrol-step = 'DISP'.
        ELSE.
          callcontrol-step = 'EXIT'.
        ENDIF.
        EXIT. "Don't process STEP DISP additionally in this call.
      ENDIF.
    4) save and activate this function module...
    5) go to se11 and create "Elementary srch hlp"....
    6) fill out all the necessary fields...i am assuming that you already know how to create the search helps...
    look for this field: "Search help exit" and put your function name which you created in the above steps...
    in this example i have: ZF4IF_SHLP_EXIT_pernr....
    7) create and activate the search help....
    hope this helps...i just tested this and it is working for me....
    Thanks..
    AS...

  • Need help on oracle sql query

    Hi team,
    Please help me on below query,
    I have table like given below
    Tran_Id  tran_date   amount. Actorid
       1.         10-apr-15.   100.         1
       2.         11-apr-15.   100.         1
       3.         11-apr-15.   900.         1
       4.         12-apr-15.   100.         1
       5.         13-apr-15.   350.         1
       6.         14-apr-15.   400.         1
    Now please find the query,
    I want all the actor ids whos tran amount
    >1500 and the  date when the tran amount
    Has breached
    Ex:
    Actor-id.  Breached-date.    Total
      1.              13-apr-15.            1900
    How can I write a query for above requirement?
    Regards,
    Rajendra

    Your solution (same as Saubhik's) is incorrect. Look at source data - multiple transactions can occur same day. Therefore, your qury will return wrong results if breached amount is 1000:
    with trans as (
    select  1  tran_Id, to_date('10-apr-15', 'dd-mon-yy') tran_date,  100 amount, 1 actorid from dual union all
    select  2,  to_date('11-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
    select  3,  to_date('11-apr-15', 'dd-mon-yy'), 900, 1 from dual union all
    select  4,  to_date('12-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
    select  5,  to_date('13-apr-15', 'dd-mon-yy'), 350, 1 from dual union all
    select  6,  to_date('14-apr-15', 'dd-mon-yy'), 400, 1 from dual union all
    select  7,  to_date('12-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    select  8,  to_date('13-apr-15', 'dd-mon-yy'), 1200, 2 from dual union all
    select  9,  to_date('14-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    select  10,  to_date('15-apr-15', 'dd-mon-yy'), 300, 2 from dual
    trans_running_tot as (
    select tran_id, tran_date,
      sum(amount) over (partition by actorid order by tran_date) tot_amt, actorid
    from trans
    trans_ranked as (
    select actorid,tran_id, tran_date,
      rank() over (partition by actorid order by tot_amt) rk
    from trans_running_tot
    where tot_amt > 1000
    select * from trans_ranked where rk=1
       ACTORID    TRAN_ID TRAN_DATE         RK
             1          2 11-APR-15          1 -- here total amount was only 200
             1          3 11-APR-15          1
             2          8 13-APR-15          1
    SQL>
    As you can see, 2 rows were returned for actor 1. Why? Default for analytic ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Therefore, all rows with same transation_date will fall into same window:
    SQL>  with trans as (
      2   select  1  tran_Id, to_date('10-apr-15', 'dd-mon-yy') tran_date,  100 amount, 1 actorid from dual union all
      3   select  2,  to_date('11-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
      4   select  3,  to_date('11-apr-15', 'dd-mon-yy'), 900, 1 from dual union all
      5   select  4,  to_date('12-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
      6   select  5,  to_date('13-apr-15', 'dd-mon-yy'), 350, 1 from dual union all
      7   select  6,  to_date('14-apr-15', 'dd-mon-yy'), 400, 1 from dual union all
      8   select  7,  to_date('12-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
      9   select  8,  to_date('13-apr-15', 'dd-mon-yy'), 1200, 2 from dual union all
    10   select  9,  to_date('14-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    11   select  10,  to_date('15-apr-15', 'dd-mon-yy'), 300, 2 from dual
    12   )
    13  select tran_id, tran_date,
    14    sum(amount) over (partition by actorid order by tran_date) tot_amt, actorid
    15  from trans
    16  /
       TRAN_ID TRAN_DATE    TOT_AMT    ACTORID
             1 10-APR-15        100          1
             2 11-APR-15       1100          1
             3 11-APR-15       1100          1
             4 12-APR-15       1200          1
             5 13-APR-15       1550          1
             6 14-APR-15       1950          1
             7 12-APR-15        300          2
             8 13-APR-15       1500          2
             9 14-APR-15       1800          2
            10 15-APR-15       2100          2
    10 rows selected.
    SQL>
    So correct solution is to ORDER BY transation id. Also, just in case if amount can be 0, we should add tranaction id when ordering by sum:
    with trans as (
    select  1  tran_Id, to_date('10-apr-15', 'dd-mon-yy') tran_date,  100 amount, 1 actorid from dual union all
    select  2,  to_date('11-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
    select  3,  to_date('11-apr-15', 'dd-mon-yy'), 900, 1 from dual union all
    select  4,  to_date('12-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
    select  5,  to_date('13-apr-15', 'dd-mon-yy'), 350, 1 from dual union all
    select  6,  to_date('14-apr-15', 'dd-mon-yy'), 400, 1 from dual union all
    select  7,  to_date('12-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    select  8,  to_date('13-apr-15', 'dd-mon-yy'), 1200, 2 from dual union all
    select  9,  to_date('14-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
    select  10,  to_date('15-apr-15', 'dd-mon-yy'), 300, 2 from dual
    trans_running_tot as (
    select tran_id, tran_date,
      sum(amount) over (partition by actorid order by tran_id) tot_amt, actorid
    from trans
    trans_ranked as (
    select actorid,tran_id, tran_date,
      rank() over (partition by actorid order by tot_amt,tran_id) rk
    from trans_running_tot
    where tot_amt > 1000
    select * from trans_ranked where rk=1
       ACTORID    TRAN_ID TRAN_DATE         RK
             1          3 11-APR-15          1
             2          8 13-APR-15          1
    SQL>
    SY.

  • Need help in the sql query

    i have a table
    source table :
    create table order(name_a varchar2(100),intid number);
    insert into order values('a',1);
    insert into order values('b',1);
    insert into order values('c',1);
    insert into order values('d',1);
    insert into order values('e',2);
    insert into order values('f',2);
    insert into order values('g',2);
    i need a query , which result in the below output :
    if i look for intid=1 the query should give a,b,c,d
    if i look for intid=2 the query should give f,g
    Thanks

    Hi,
    781649 wrote:
    i have a table
    source table :
    create table order(name_a varchar2(100),intid number);
    insert into order values('a',1);
    insert into order values('b',1);
    insert into order values('c',1);
    insert into order values('d',1);
    insert into order values('e',2);
    insert into order values('f',2);
    insert into order values('g',2);Thanks for posting the CREATE TABLE and INSERT statements; it's very helpful.
    i need a query , which result in the below output :
    if i look for intid=1 the query should give a,b,c,d
    if i look for intid=2 the query should give f,gDid you mean <b>e</b>,f,g ?
    That's called String Aggregation , and how to do it depends on your version of Oracle, and your exact requirements.
    See thie following page for several techniques:
    http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
    If you're using Oracle 10 (or higher), and it's important that the name_a's be in order in the output, then you can do this:
    WITH     got_r_num     AS
         SELECT     name_a
         ,     intid
         ,     ROW_NUMBER () OVER ( PARTITION BY  intid
                                   ORDER BY          name_a
                           )         AS r_num
         FROM     order_table                    -- ORDER is not a good table name
         WHERE     intid     IN (1)                    -- Optional
    SELECT     intid
    ,     SUBSTR ( SYS_CONNECT_BY_PATH (name_a, ',')
                , 2
                )     AS name_a_list
    FROM     got_r_num
    WHERE     CONNECT_BY_ISLEAF     = 1
    START WITH     r_num     = 1
    CONNECT BY     r_num     = PRIOR r_num + 1
         AND     intid     = PRIOR intid
    ;Starting in Oracle 11.2, LISTAGG is better.
    This does not assume that you are getting the output only for a single intid at a time. You can get any number of them in a suingle query. Of course, that number can be 1 if that's what you want.
    Edited by: Frank Kulash on Mar 24, 2011 12:19 PM

  • Help with JSTL sql query

    i have a query that i want to pass a paramater to the query goes like this
    <sql:query var = "user" >
    SELECT AMOUNT,flag FROM SAVINGS_ACTIVITY_DETAILS WHERE ACCOUNT_ID =? AND AMOUNT >200000 AND Flag =1 AND ACCOUNT_ACTION_ID =6 AND Treated =0 ORDER BY created_date DESC
    <sql:param value="${test.accountId}"/>
    </sql:query>
    this will give an error on TLD attribute.................and i tested the value with the following code and it worked
    <c:set value="${test.accountId}" var="u"/>
    <c:out value="${u}"/>
    this will print out the value nicely now i need a way to be able to pass this value to the sql query
    Thanks

    Which version of jstl are you using? == JSTL1.1
    However the other two questions remain unanswered.
    What server are you using? Version?
    How are you importing the tag library?
    You can find out the server info with this snippet of a JSP:
    Working with server: <%= application.getServerInfo() %><br>
    Servlet Specification: <%= application.getMajorVersion() %>.<%= application.getMinorVersion() %> <br>
    JSP version: <%= JspFactory.getDefaultFactory().getEngineInfo().getSpecificationVersion() %><br>
    Java Version: <%= System.getProperty("java.version") %><br>

  • Help on JSTL sql:query / tag

    Hi.....
    Currently i am trying to query a date from MSSQL using <sql> tag. I had tested in MSSQL on this SQL statement which is:-
    SELECT * FROM hr_leave WHERE startDate LIKE 'Apr 20 2006%'
    It can query my MSSQL datetime.
    Then , I apply this query inside my JSP/JSTL page which is :-
    <%@ include file="/common/header.jsp" %>
    <%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
    <jsp:useBean id="now" class="java.text.SimpleDateFormat"/> <!-- get current date -->
    <c:set var="userid" value="${sessionScope.currentUser.id}"/> <!-- get current user id -->
    <c:set var="dates"><fmt:formatDate value="${now}" type="DATE" pattern="MMM dd yyyy"/></c:set>
    <sql:setDataSource var="ds" driver="com.microsoft.sqlserver.jdbc.SQLServerDriver" url="jdbc:sqlserver://192.168.250.86:1223;DatabaseName=eleavedb;SelectMethod=cursor" user="sa" password="sapassword"/>
    <sql:query var="countLeave" dataSource="${ds}">
    SELECT * FROM hr_leave_entry WHERE startDate LIKE (?, '%')
    <sql:param value="${dates}"/>
    </sql:query>
    From the code above it displayed an an error for me. I am worried whether my select statement and my way of using the '%' symbol is it not correct.
    Can anyone guide me? Thank You!

    And the error was?
    No, that sql does not look valid the way that you have written it.
    Parameters are NOT copied/pasted into sql strings. They replace the value directly. So the correct sql would be
    SELECT * FROM hr_leave_entry WHERE startDate LIKE ?
    You would need to actually pass the parameter as 'Apr 20 2006%'

  • Help! with sql:query  statement

    Using JSTL, I am trying to select two tables from two different database. The tables do not contain the same information but just happen to have the same name "desc" . I have something like this.
    <sql:query var="result">
    Select  trim(DATA.desc), trim(TEXT.desc) from DATA, TEXT
    </sql:query>
    <c:forEach items="${result.rows}" var="row1">
    <c:out value="${row1}"/>
    </c:forEach>It displays the second table which is TEXT.desc and ignores the other DATA.desc.
    How do I display them both?

    Is there a way to query it and output the result in an array?Sure - you can use the call to rowsByIndex which returns a 2d array:
    I think the following should work
    <sql:query var="result">
    Select  trim(DATA.desc) as dataDesc, trim(TEXT.desc) as textDesc from DATA, TEXT
    </sql:query>
    <c:forEach items="${result.rowsByIndex}" var="row1">
    <c:out value="${row1[0]}"/>.  <c:out value="${row1[1]}"/>
    </c:forEach>However the previous code should have worked. I would double check your data and query that it is returning the data you think it is.
    Cheers,
    evnafets

  • Help needed for SQL query

    hello ,
    I am a beginner in terms of writing sql queries. I hope some body can help me out.
    I have two tables
    mysql> desc user_group_t;
    ---------------------------------------------------+
    | Field | Type | Null | Key | Default | Extra |
    ---------------------------------------------------+
    | userAccountId | char(8) | | PRI | | |
    | groupId | char(8) | | PRI | | |
    ---------------------------------------------------+
    2 rows in set (0.00 sec)
    mysql> desc group_t;
    ---------------------------------------------------+
    | Field | Type | Null | Key | Default | Extra |
    ---------------------------------------------------+
    | id | char(8) | | PRI | | |
    | name | char(50) | YES | | NULL | |
    | email | char(100) | YES | | NULL | |
    | description | char(254) | YES | | NULL | |
    | parentId | char(8) | YES | | NULL | |
    | creatorId | char(8) | YES | | NULL | |
    | createDate | char(20) | YES | | NULL | |
    | updateDate | char(20) | YES | | NULL | |
    | updatorId | char(8) | YES | | NULL | |
    ---------------------------------------------------+
    9 rows in set (0.00 sec)
    what I want is list of all groups with id,name and #of members(which is the # of rows in the user_group_t for any given id). Importantly I need the groups with 0 members also to be listed. In short my output should contain exactly the same number of rows as in group_t table with an additional column indicating # of members for that group.
    Any help would be greatly appreciated.
    Thanks in Advance.
    -Vasanth

    Thanks Donald,
    Actually I figured it out, with the following query:
    select id,name,sum(if(groupid is not null,1,0)) as members from group_t left join user_group_t on id=groupid group by id;
    I tried your solution, but mysql says there is an error at '+' . Anyway I modified your solution to the one below and it worked.
    select a.id, a.name, count(b.groupid) from group_t a left join user_group_t b on a.id=b.groupid group by a.id, a.name;
    I tried that before but then I used Count(*) instead of count on groupid. Your solution is elagant and I will go with yours.
    Thanks again.
    Vasanth

  • Help required in SQL query

    I have a table and cols as below:
    START DATE     TOTAL DAYS
    10/11/2011 15:00      1
    10/15/2011 5:00      1
    12/22/2011 10:00     1
    12/22/2011 11:00     2
    12/30/2011 10:00     1
    1/1/2012 1:00     1
    1/1/2012 10:00     1
    1/1/2012 16:00     2
    1/2/2012 14:00     1
    1/3/2012 15:00     1
    1/4/2012 15:00     2
    1/4/2012 18:00     1
    I need to query where the values from the above table
    should return values like below:
    I tried many ways but could not find suitable solution.
    Kindly help me in this regard.
    START DATE     TOTAL DAYS
    10/11/2011 15:00     1
    10/15/2011 5:00     1
    12/22/2011 11:00     2
    12/30/2011 10:00     1
    1/1/2012 16:00      2
    1/2/2012 14:00      1
    1/3/2012 15:00      1
    1/4/2012 15:00     2
    ultimate goal is to sum up the all numbers TOTAL DAYS column in the second table... All task should be handled in single query. I cannot use java coding to handle this as my requirement needs to be included in the query which exists already.
    Edited by: 915175 on Feb 16, 2012 11:02 PM

    select trunc(start_date), max(start_date), max(total_days) from tablename
    group by trunc(start_date);Please check below Test done at my local site with you data:
    SQL>
    SQL> with tablename as
      2  (
      3  select to_date('10/11/2011 15:00' , 'mm/dd/yyyy hh24:mi') start_date,  1 total_days from dual union all
      4  select to_date('10/15/2011 5:00' , 'mm/dd/yyyy hh24:mi') start_date,  1 total_days from dual union all
      5  select to_date('12/22/2011 10:00' , 'mm/dd/yyyy hh24:mi') start_date,  1 total_days from dual union all
      6  select to_date('12/22/2011 11:00' , 'mm/dd/yyyy hh24:mi') start_date,  2 total_days from dual union all
      7  select to_date('12/30/2011 10:00' , 'mm/dd/yyyy hh24:mi') start_date,  1 total_days from dual union all
      8  select to_date('1/1/2012 1:00' , 'mm/dd/yyyy hh24:mi') start_date,  1 total_days from dual union all
      9  select to_date('1/1/2012 10:00' , 'mm/dd/yyyy hh24:mi') start_date,  1 total_days from dual union all
    10  select to_date('1/1/2012 16:00' , 'mm/dd/yyyy hh24:mi') start_date,  2 total_days from dual union all
    11  select to_date('1/2/2012 14:00' , 'mm/dd/yyyy hh24:mi') start_date,  1 total_days from dual union all
    12  select to_date('1/3/2012 15:00' , 'mm/dd/yyyy hh24:mi') start_date,  1 total_days from dual union all
    13  select to_date('1/4/2012 15:00' , 'mm/dd/yyyy hh24:mi') start_date,  2 total_days from dual union all
    14  select to_date('1/4/2012 18:00' , 'mm/dd/yyyy hh24:mi') start_date,  1 total_days from dual
    15  )
    16  select  TO_CHAR(max(start_date),'MM/DD/YYYY HH24:MI') start_date , max(total_days) total_days from tablename
    17  group by trunc(start_date);
    START_DATE       TOTAL_DAYS
    10/15/2011 05:00          1
    01/03/2012 15:00          1
    12/30/2011 10:00          1
    01/01/2012 16:00          2
    10/11/2011 15:00          1
    12/22/2011 11:00          2
    01/04/2012 18:00          2
    01/02/2012 14:00          1
    8 rows selected.
    SQL>Regards,
    Dipali..
    Update: Added test done at my database..
    Edited by: Dipali Vithalani on Feb 16, 2012 11:18 PM

Maybe you are looking for

  • Add a watermark, the hard way

    Hi. I've been drooling over the Acrobat 7.0 SDK documentation. It talks about an addWatermarkFromFile() function in JavaScript. You lucky, lucky, lucky people. I have Acrobat 6.0 (Pro). Ugh. You can add a watermark in the application, but there is no

  • How to execute exact match & contains text search simultaneoulsy in Oracle 10g

    Hi, We have scenario where there are more than 50 million rows in a table with description column length as 1000 character. We have a web interface from where we generate a rule of comma separated keywords like "Standard", Single, Cancel, "deal"    &

  • PO update for SES and ME2N

    I have following situation: PO created for $5000 for service- SES created for 1070, MIRO created and paid for 1070 ( $ 70 is or tax) PO history tab shows SES for $1070: GR for $1070 and IR for $1070 However, when I go into ME2N it shows Still to be d

  • Any one prepar integration test cases in SAP XI

    Hi, any one help me ,how to prepare integration Test cases in SAP XI bye suresh

  • Is it possible to steer the mouse in java?

    Is it possible to steer the mouse in java? Thanks!