SQL Query - Max Date - Group By

Please see SQL below - this code is counting customers and grouping by their tenure since activation
However the table FACT_TRANS I am linking to contains multiple transactions for different dates and I only want to select the latest date.
How can I return only the latest transaction from the FACT_TRANS table as the code below (In Bold)is not returning the correct number of records
SELECT TO_NUMBER(MONTHS_BETWEEN(To_DATE(a.DATE_KEY, 'yyyymmdd' ),
TO_DATE(ADD_MONTHS((LAST_DAY(c.DATE_JOIN)+1),-1),'dd-mm-yyyy')) -24000, '999') AS TENURE,
SUM(DECODE(A.RESULT_MNTHM12_VALUE,0,0,1)) AS M12,
SUM(DECODE(A.RESULT_MNTHM11_VALUE,0,0,1)) AS M11,
SUM(DECODE(A.RESULT_MNTHM10_VALUE,0,0,1)) AS M10,
SUM(DECODE(A.RESULT_MNTHM9_VALUE,0,0,1)) AS M9,
SUM(DECODE(A.RESULT_MNTHM8_VALUE,0,0,1)) AS M8,
SUM(DECODE(A.RESULT_MNTHM7_VALUE,0,0,1)) AS M7,
SUM(DECODE(A.RESULT_MNTHM6_VALUE,0,0,1)) AS M6,
SUM(DECODE(A.RESULT_MNTHM5_VALUE,0,0,1)) AS M5,
SUM(DECODE(A.RESULT_MNTHM4_VALUE,0,0,1)) AS M4,
SUM(DECODE(A.RESULT_MNTHM3_VALUE,0,0,1)) AS M3,
SUM(DECODE(A.RESULT_MNTHM2_VALUE,0,0,1)) AS M2,
SUM(DECODE(A.RESULT_MNTHM1_VALUE,0,0,1)) AS M1,
SUM(DECODE(A.CURRENT_RESULT_VALUE,0,0,1)) AS M0
FROM FACT_RESULT_VW a,
PLAN_VW b,
SUB_VW c ,
CUST_VW d,
FACT_TRANS e,
WHERE e.DATE_TRANS IN (SELECT MAX (FACT_TRANS.DATE_TRANS) FROM FACT_TRANS )+
AND a.PP_KEY = b.PP_key
AND a.ID = c.ID
AND c.CUST_ID = d.CUST_ID
AND c.ID = E.ID
AND c.DATE_JOIN >= To_DATE('01-09-2002 00:00:00', 'dd-mm-yyyy hh24:mi:ss' )
AND c.DATE_JOIN < To_DATE('01-07-2010 00:00:00', 'dd-mm-yyyy hh24:mi:ss' )
AND a.DATE_KEY = 20100601
AND A.PEF_ID = 1
GROUP BY TO_NUMBER(MONTHS_BETWEEN(To_DATE(a.DATE_KEY, 'yyyymmdd' ),
     TO_DATE(ADD_MONTHS((LAST_DAY(c.DATE_JOIN)+1),-1),'dd-mm-yyyy')) -24000, '999')

Hi,
Whenever you have a question, post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
Simplify the problem as much as possible.
Would you have the same problem if only two tables, fact_result_vw and fact_trans, were involved? Then post a question involving only those two tables. Once you have a solution for the simplified problem, adding the other tables will be easy.
Would the problem be essentially the same if you were pivoting only 2 or 3 columns, instead of 13? Then post a question where you're only pivoting 2 or 3 columns. Once you have a solution, adding the others will be easy.
787771 wrote:
Please see SQL below - this code is counting customers and grouping by their tenure since activation
However the table FACT_TRANS I am linking to contains multiple transactions for different dates and I only want to select the latest date.
How can I return only the latest transaction from the FACT_TRANS table as the code below (In Bold)is not returning the correct number of recordsDo you want only the latest transaction from the fact_trans table, or the latest transaction for each customer ?
What if there's a tie, and the same customer has two (or more) transactions at the same date, and none later?
Since you're not using any of the data from the fact_trans table, the effect is just to eliminate customers who are not in fact_trans. You can do that more simply with an IN or EXISTS sub-query.
If you really do need something from the fact_trans table in the main table, then one way you can get the results you want is to use the analytic RANK (or ROW_NUMBER) function to number the rows in fact_trans by trans_date (latest first), with a separate set of numbers (1, 2, 3, ...) for each customer, like this:
WITH     fact_trans_1     AS
     SELECT     id     -- all columns that you need
     ,     RANK () OVER ( PARTITION BY  id
                      ORDER BY          date_trans     DESC
                    )     AS r_num
     FROM     fact_trans
SELECT        TO_NUMBER(MONTHS_BETWEEN(To_DATE(a.DATE_KEY, 'yyyymmdd' ),
       TO_DATE(ADD_MONTHS((LAST_DAY(c.DATE_JOIN)+1),-1),'dd-mm-yyyy')) -24000, '999') AS TENURE,
       SUM(DECODE(A.RESULT_MNTHM12_VALUE,0,0,1)) AS M12,
       SUM(DECODE(A.RESULT_MNTHM11_VALUE,0,0,1)) AS M11,
       SUM(DECODE(A.RESULT_MNTHM10_VALUE,0,0,1)) AS M10,
       SUM(DECODE(A.RESULT_MNTHM9_VALUE,0,0,1)) AS M9,
       SUM(DECODE(A.RESULT_MNTHM8_VALUE,0,0,1)) AS M8,
       SUM(DECODE(A.RESULT_MNTHM7_VALUE,0,0,1)) AS M7,
       SUM(DECODE(A.RESULT_MNTHM6_VALUE,0,0,1)) AS M6,
       SUM(DECODE(A.RESULT_MNTHM5_VALUE,0,0,1)) AS M5,
       SUM(DECODE(A.RESULT_MNTHM4_VALUE,0,0,1)) AS M4,
       SUM(DECODE(A.RESULT_MNTHM3_VALUE,0,0,1)) AS M3,
       SUM(DECODE(A.RESULT_MNTHM2_VALUE,0,0,1)) AS M2,
       SUM(DECODE(A.RESULT_MNTHM1_VALUE,0,0,1)) AS M1,
       SUM(DECODE(A.CURRENT_RESULT_VALUE,0,0,1)) AS M0
FROM        FACT_RESULT_VW      a,
       PLAN_VW           b,
       SUB_VW           c,
       CUST_VW           d,
       FACT_TRANS_1          e,
WHERE        e.DATE_TRANS IN (SELECT MAX (FACT_TRANS.DATE_TRANS) FROM FACT_TRANS )
AND       e.r_num     = 1
AND        a.PP_KEY      = b.PP_key
AND        a.ID           = c.ID
AND       c.CUST_ID      = d.CUST_ID
AND       c.ID           = E.ID
AND       c.DATE_JOIN       >= To_DATE('01-09-2002 00:00:00', 'dd-mm-yyyy hh24:mi:ss' )
AND       c.DATE_JOIN      <  To_DATE('01-07-2010 00:00:00', 'dd-mm-yyyy hh24:mi:ss' )
AND       a.DATE_KEY = 20100601
AND       A.PEF_ID = 1
GROUP BY  TO_NUMBER(MONTHS_BETWEEN(To_DATE(a.DATE_KEY, 'yyyymmdd' ),
       TO_DATE(ADD_MONTHS((LAST_DAY(c.DATE_JOIN)+1),-1),'dd-mm-yyyy')) -24000, '999')I hope this answers your question.
If not, post some sample data (CREATE TABLE and INSERT statements) and the results you want from that data.

Similar Messages

  • Multiple SQL Query as Data Source

    I have an SQL Query as Data Source of my Crystal Report. It combine the contents of two tables.
    I want to do another SQL query based on the previuos SQL Query.
    Can I do this in CR ? How I can reference the new SQL query to the main SQL query ?
    Thanks,
    Gabriel

    This is my main Query
    SELECT
    SBO_001.dbo.JDT1.Account,
    sum(SBO_001.dbo.JDT1.SYSDeb - SBO_001.dbo.JDT1.SYSCred) AS Balance_001,
    0 as Balance_004
    FROM SBO_001.dbo.JDT1
    GROUP BY SBO_001.dbo.JDT1.Account
    UNION
    SELECT
    SBO_004.dbo.JDT1.Account,
    0 as Balance_001,
    sum(SBO_004.dbo.JDT1.SYSDeb - SBO_004.dbo.JDT1.SYSCred) AS Balance_004
    FROM SBO_004.dbo.JDT1
    GROUP BY SBO_004.dbo.JDT1.Account
    This is a result
    Account     Balance_001     Balance_004
    80800005     0     -431.67
    80800005     590121.07           0
    80800006     -3621028.250            0     
    88780056     5000.00                    0
    90731001     0                          174780.11     
    I want to obtain this result
    Account     Balance_001            Balance_004
    80800005     590121.07             -431.67
    80800006     -3621028.250            0     
    88780056     5000.00                    0
    90731001     0                          174780.11     
    How I Can modify this Query?
    Thanks,
    Edited by: gablus on Aug 7, 2009 1:43 AM

  • How to write a SQL Query without using group by clause

    Hi,
    Can anyone help me to find out if there is a approach to build a SQL Query without using group by clause.
    Please site an example if is it so,
    Regards

    I hope this example could illuminate danepc on is problem.
    CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
    CREATE OR REPLACE FUNCTION GET_ARR return my_array
    as
         arr my_array;
    begin
         arr := my_array();
         for i in 1..10 loop
              arr.extend;
              arr(i) := i mod 7;
         end loop;
         return arr;
    end;
    select column_value
    from table(get_arr)
    order by column_value;
    select column_value,count(*) occurences
    from table(get_arr)
    group by column_value
    order by column_value;And the output should be something like this:
    SQL> CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
      2  /
    Tipo creato.
    SQL>
    SQL> CREATE OR REPLACE FUNCTION GET_ARR return my_array
      2  as
      3   arr my_array;
      4  begin
      5   arr := my_array();
      6   for i in 1..10 loop
      7    arr.extend;
      8    arr(i) := i mod 7;
      9   end loop;
    10   return arr;
    11  end;
    12  /
    Funzione creata.
    SQL>
    SQL>
    SQL> select column_value
      2  from table(get_arr)
      3  order by column_value;
    COLUMN_VALUE
               0
               1
               1
               2
               2
               3
               3
               4
               5
               6
    Selezionate 10 righe.
    SQL>
    SQL> select column_value,count(*) occurences
      2  from table(get_arr)
      3  group by column_value
      4  order by column_value;
    COLUMN_VALUE OCCURENCES
               0          1
               1          2
               2          2
               3          2
               4          1
               5          1
               6          1
    Selezionate 7 righe.
    SQL> Bye Alessandro

  • How to compare result from sql query with data writen in html input tag?

    how to compare result
    from sql query with data
    writen in html input tag?
    I need to compare
    user and password in html form
    with all user and password in database
    how to do this?
    or put the resulr from sql query
    in array
    please help me?

    Hi dejani
    first get the user name and password enter by the user
    using
    String sUsername=request.getParameter("name of the textfield");
    String sPassword=request.getParameter("name of the textfield");
    after executeQuery() statement
    int exist=0;
    while(rs.next())
    String sUserId= rs.getString("username");
    String sPass_wd= rs.getString("password");
    if(sUserId.equals(sUsername) && sPass_wd.equals(sPassword))
    exist=1;
    if(exist==1)
    out.println("user exist");
    else
    out.println("not exist");

  • Problem with a SQL query involving dates

    I have a database with each task made by a developer in the company's systems, with 2 fields to determine the duration of the tasks: begin_date and end_date, both Dates. Now I have to make an SQL query returning the total of hours each one worked counting every task, so I'm using something like this (simplifying):
    select user_id, sum(end_date - begin_date)
    from task
    group by user_id
    but I get a weird fractional number. How do I do this query?

    What database are you using? Oracle?
    The weird fractional number is probably the difference between the dates in days. If you want it in hours, try multiplying it with 24.
    select user_id, sum(end_date - begin_date) * 24
    from task
    group by user_id

  • T-SQL Query Duplicate dates.

    A table is called ‘ImportEvents’ There are currently 50 records in this table.  The user has the ability to enter the ‘Import Date’ manually and multiple imports could have happened on the same date.  What SQL query would you use to identify
    a list of all the dates on which an upload has occured without duplicates?

    If I want the number of Imported dates that don't have duplicate values how could I aggregate the query ?
    In sumo -
    50 records say 18 records where created on one date and 32 on 32 different dates how can I retrieve the list of 33 records based on the Imported Date.
    DECLARE @ImportEvents TABLE (importDate date)
    INSERT INTO @ImportEvents (importDate)
    VALUES ('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),
    ('2014-01-02'),('2014-01-03'),('2014-01-04'),('2014-01-05'),('2014-01-06'),
    ('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07')
    select importDate
    From @ImportEvents
    group by importDate
    having sum(importDate) = 1
    Thanks
    Richard

  • Report from sql query invalid date condition

    Hi, I created a Reports From SQL Query. My sql is like
    "select column1, column2
    from myschema.tablename
    where mydate > :p_date1 and mydate < :p_date2"
    I am using portal with turkish and english option. If I pass p_date paramaters 'dd-MON-yyyy' format
    (for example p_date1 = 23-MAR-2003 p_date2 = 26-APR-2003) in english mode portlet is return correct result,
    in turkish mode 'No Row Returned'. I changed my sql statement with
    "select column1, column2
    from myschema.tablename
    where to_date(mydate,'dd/mm/yyy') > to_date(:p_date1,'dd/mm/yyy') and to_date(mydate) < to_date(:p_date2,'dd/mm/yyyy')"
    and I pass p_date parameters 'dd/mm/yyyy' format (for example p_date1 = 23/03/2003 p_date2 = 26/04/2003)
    but now turkish and english mode No row returned.
    How may I write correct sql statament. My database NLS_DATE_FORMAT=DD/MM/YYYY and NLS_LANGUAGE=TURKISH.
    thanks.

    Hi,
    Try this for turkish mode:
    Case 1: the 'mydate' column has a kind of a char data type (like char, varchar or varchar2)
    and a value like '30/03/2003'
    "select column1, column2
    from myschema.tablename
    where
    to_date(mydate,'DD/MM/YYYY') > :p_date1
    and
    to_date(mydate,'DD/MM/YYYY') < :p_date2"
    Case 2: the mydate column has a date type:
    "select column1, column2
    from myschema.tablename
    where
    mydate > :p_date1
    and
    mydate < :p_date2"
    In both cases use the following parameter values:
    p_date1 = 23/03/2003
    p_date2 = 26/04/2003
    This should work
    Thanks
    Peter

  • SQL query generating data in SQL management studio but not in CUIC interface

    Hello,
    I'm working on a UCCE 9.0 system
    I created SQL query for a  report.
    Whenever I run the query inside the SQL management studio, it works and generates data, but when I run it in the CUIC interface it works but generates nothing. As you can see in the below snapshot, it contains 209 records that are not being displayed.
    Any help would be greatly apprciated

    Is it a custom report ? Can you right click on your Custom Report and click on Edit Views. You need to check whether you have Grid Headers Listed.
    Regards,
    Senthil

  • PL/SQL function body return sql query, no data found problem

    Hi all,
    we are trying to build a dynamic report based on item selection by user. we are using SQL Query (PL/SQL function body returning SQL query). However when a user change the item and submit the page . The following error appears.
    ORA-01403: no data found.
    our query is so simple
    declare
    l_query varchar2(30000) default 'select id from chw';
    begin
    if(:P11_PARA=1) then
    l_query:='select name from chw';
    end if;
    return l_query;
    end;
    any quick help please.

    Hello Mike,
    I tried it, the problem still exists.
    ORA-01403: no data found
    my new code is
    declare
    l_query varchar2(30000) default 'select id from chw';
    begin
    if (nvl(TO_NUMBER(:P11_PARA),0) = 1) then
    l_query:='select name from chw';
    end if;
    return (l_query);
    end;
    note, there is no process in this page.
    Edited by: M.Jabr on Oct 14, 2009 6:13 AM

  • SQL Query using DATS data type

    Hello people,
    I have a table 'TableA' with a column 'xpto' that has DATS data type.
    A lot of lines in this table has this field empty.
    I have to create a SQL query to select those lines with this field not empty.
    Select * from TableA
    where xpto is not null
    It does not work.... The result is all the lines in the table.
    What is wrong?
    Thanks!

    Easiest way to do this is :
    constants l_xpto   type tableA-xpto  value is initial
    Select * from TableA
    where xpto ne l_xpto.
    You can see the NULL/NOT NULL settings for the column through SE11
    Utilities -> Database Object -> Display.
    I tend to set the "Initial Value" flag when adding columns to tables, which creates the database column as NOT NULL with a default value (whatever SAP considers the initial value for that datatype). I think SAP does this by default, but I've had issues where it hasn't so I do this to ensure consistency
    Chris Bain

  • Setting Default value with SQL Query as Data Model

    Hi All,
    I am developing report based on SQL query.date set as 'SQL Query'. I have created two params start-date and end-date. I am fetching records from database between these two dates.
    I want to populate sysdate as a default values. I do not want to use datatemplate approach i mean using beforeReport trigger.
    Thansk,
    Vara

    Hi Vara,
    To set the default value for one of your parameters to SYSDATE you need to enter:
    {$SYSDATE()$}
    in the Default Value text box
    Is this what you require?
    Cheers
    Andy

  • How to display the SQL query's date parameters to the report

    Hi all,
    I'd like to take the date parameters that are contained in my query and have them appear on the report and/or have the sysdate appear on the report. Any ideas on how to do this? Thanks!

    Hi..
    To display parameters which are part of SQl Query in the output..
    http://blogs.oracle.com/xmlpublisher/2008/07/where_are_the_parameter_values.html
    HTH..

  • Trying to get max date grouped by type

    hello,
    i have a request table with:
    request name
    request start date
    The requests run daily so i have multiple records. In answers i want to display request name and the max(request start date), grouped by request name. Is it possible to due this in answers only? if i must use the repository how do i do it? I'm new to building subject areas.

    You can do this in answers only, If you dont have access to RPD.
    Sol1: Create a report with two columns request name,request start date. Open pivot table and add request start date to measures and apply Aggregation of Max on date.
    sol2: Create a report with two columns request name,request start date, Change the Fx of request start date to max(request start date by request name) . This way table view also show request max date by request names.

  • Error While execting SQL Query : No Data to Read from Sockt.

    Hi,
    I am getting the Error "No Data To Read from Sockt" While executing SQL Query from PL/SQL Developer and same error i am getting while i trying on Toad and SQL*Plus also.
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
    PL/SQL Release 10.2.0.3.0 - Production
    CORE     10.2.0.3.0     Production
    TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production Pls suggest !!
    Thanks n Regards
    Rj

    Try to connect without tnsnames. So try the basic connection from SQLDeveloper.
    If it works, you have to verify your tnsnames.ora
    Are you th only person to have this connection problem or all users meet this error?
    Does this connection worked before, is it a new connection?
    What changes occured since the connection is out of service.

  • SQL Query on Date Range

    Hi, I am using Oracle 10g. I want a query which gives me below output.
    Data Setup
    ========
    create table t_date_range (
    ID     number (2),
    start_date     date,
    end_date     date);
    insert into t_date_range values (1,to_date('20110101', 'YYYYMMDD'),to_date('20110331', 'YYYYMMDD'));
    insert into t_date_range values (2,to_date('20110401', 'YYYYMMDD'),to_date('20110531', 'YYYYMMDD'));
    insert into t_date_range values (3,to_date('20110701', 'YYYYMMDD'),to_date('20110731', 'YYYYMMDD'));
    insert into t_date_range values (4,to_date('20110901', 'YYYYMMDD'),to_date('20111130', 'YYYYMMDD'));
    insert into t_date_range values (5,to_date('20111201', 'YYYYMMDD'),to_date('20111231', 'YYYYMMDD'));
    commit;
    SQL> select ID, to_char(start_date,'DD-MON-YYYY') START_DATE, to_char(end_date,'DD-MON-YYYY') END_DATE from t_date_range;
    ID START_DATE END_DATE
    1 01-JAN-2011 31-MAR-2011
    2 01-APR-2011 31-MAY-2011
    3 01-JUL-2011 31-JUL-2011
    4 01-SEP-2011 25-OCT-2011
    5 26-OCT-2011 30-NOV-2011
    6 01-DEC-2011 31-DEC-2011
    6 rows selected.
    I want result in this form:
    START_DATE END_DATE
    01-JAN-2011 31-MAY-2011
    01-JUL-2011 31-JUL-2011
    01-SEP-2011 31-DEC-2011
    Means if there is a difference of exact one day between "start_date of 2nd row" and "end_date of first row" then make a single row as shows in above results set.
    Thanks!

    Hi,
    Solomon Yakobson wrote:
    Keep in mind, Franks's solution assumes date ranges do not overlap. ...That's true. If rows can overlap, then we might need to use two sub-queries, like you did: one to see if a new group starts with this row, and another to count how many new groups have already started.
    The solution you posted assumes a relationship between id and dates. If we add a row like this to the sample data:
    insert into t_date_range values (6,to_date('20101201', 'YYYYMMDD'),to_date('20121231', 'YYYYMMDD'));that overlaps all the others, then how would that solution work?
    LAG won't work, because no matter how we sort the rows, we can't be sure that overlapping rows will be consecutive.
    Here's one way to handle overlapping rows:
    WITH     got_new_grp          AS
         SELECT     id, start_date, end_date
         ,     CASE
                  WHEN  start_date > 1 + MAX (end_date) OVER ( ORDER BY  start_date
                                                                        ,             id
                                                                        ROWS BETWEEN  UNBOUNDED PRECEDING
                                                  AND      1      PRECEDING
                  THEN  1
              END     AS new_grp
         FROM     t_date_range
    ,     got_grp          AS
         SELECT  start_date, end_date
         ,     COUNT (new_grp) OVER ( ORDER BY  start_date
                                     ,           id
                             ) AS grp
         FROM    got_new_grp
    SELECT       MIN (start_date)     AS start_date
    ,       MAX (end_date)     AS end_date
    FROM       got_grp
    GROUP BY  grp
    ORDER BY  start_date
    ;This solution uses id (assumed to be unique) just to get a consistent ordering, in case 2 (or more) rows have exactly the same start_date. It does not assume any relationship between ids and either start_date or end_date.
    I'm also assuming that start_date<=end_date on each row.
    Edited by: Frank Kulash on May 11, 2011 12:54 PM
    The above refers to the solution you oriognally posted, which was:
    with t1 as (
                select  id,
                        start_date,
                        end_date,
                        case
                          when lag(end_date) over(order by id) + 1 >= start_date then 0
                          else 1
                        end start_of_group
                  from  t_date_range
         t2 as (
                select  id,
                        start_date,
                        end_date,
                        sum(start_of_group) over(order by id) grp
                  from  t1
    select  min(start_date) start_date,
            max(end_date) end_date
      from  t2
      group by grp
      order by grp
    ;

Maybe you are looking for