SQL DISTINCT COUNT IN DATE RANGE

Dear All
Thanks for your attention.
A table is storing the task summary of each order
e.g.
Date                            | Order Number    | Task Number
2015-01-01 00:00:01   | ABC123456        | JOB001
2015-01-01 00:01:02   | ABC123456        | JOB002
2015-01-01 00:10:02   | ABC123444        | JOB001
2015-01-01 10:12:59   | ABC123456        | JOB002   (Since the job002 is not done correctly, need to work again)
2015-01-01 18:20:05   | ABC888888        | JOB001
2015-01-01 20:22:42   | ABC789456        | JOB001
2015-01-01 21:02:11   | BBB121212        | JOB002
I would like to write a single query that get the distinct count of order number in sepcific date range
result as expected in three columns:
2015-01-01
task_number            | AM | PM
JOB001         | 2    | 2
JOB002         | 1    | 1
explain the figures here:
JOB001 AM = 2 (ABC123456, ABC123444)
JOB002 AM = 1  (two records of ABC123456 count as 1 since we would like to know the number of orders)
JOB001 PM = 2  (ABC888888, ABC789456)
JOB002 PM = 1  (BBB121212)
I wrote a query get similar result but the count of order is not distinct
SELECT task_number,
AM=SUM(CASE WHEN date >= ('2015-01-01 00:00:00') AND date < ('2015-01-01 12:00:00') THEN 1 ELSE 0 END),
PM=SUM(CASE WHEN date >= ('2015-01-01 12:00:00') AND date < ('2015-01-02 00:00:00') THEN 1 ELSE 0 END)
FROM MyTable
WHERE task_number = 'JOB001'
Could anyone advise how to enhance this query to let the result become disintct of order number?
Many Thanks,
swivan

Try
select task_number,
count(distinct case when datepart(hour, [date]) >=0 and datepart(hour, [date]) < 12 then [OrderNumbers] END) as AM,
count(distinct case when datepart(hour, [date]) >=12 and datepart(hour, [date]) < 24 then [OrderNumbers] END) as PM FROM myTable
GROUP BY Task_Number
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles
Thank you very much,  short and good answer

Similar Messages

  • Distinct count on date/time field...

    Hi,
    I am trying to a distinct count on this formula that takes a date/time field and converts it to a date in order to get a distinct count of dates.  However, it's not working... say, if I have two dates are the same (the times may be different), it's counted twice.  Any suggestions?  I tried to convert this to a string thinking the evaluation may change, but no dice.  Thanks!!
    if not isnull({AVAILABILITY.PAT_ENC_CSN_ID}) then
        cstr(cdate({AVAILABILITY.SLOT_BEGIN_TIME}))
    else

    You can use the following formula...
    DateAdd("d", DateDiff("d", #1/1/1900#, {TableName.YourDateTimeField}), #1/1/1900#)
    This will set each date value to 12:00 am of it's respective day...
    So 8/16/2010   3:01:20PM would become 8/16/2010  12:00:00AM
    Now you can group on this formula field and then simply do a count on the date at the appropriate group level.
    HTH,
    Jason

  • Getting Record Count From Date Range - IDE: PLSQL Developer

    I would like to count the number of member records that fall within a specified date range based on the members effective and expiration dates and their 'elg_code'. I have posted the SQL for some sample data. What I would like to see returned is three columns of counts where the members eff_date exp_date fall within the date range specified by the SQL and have an Elg_code of ' ' (one blank space).
    So, what I would like is all members with elg_code ' ' where there eff_dt and exp_dt range falls within APR 2012, MAY 2012 & JUN 2012. So, based on the sample data I posted, Mark, where his elg_code record is ' ', his eff_dt is 1/1/2011 and his exp_dt is within APR 2012 (4/30/2012). Mark's range falls within APR 2012, but not MAY or JUNE of 2012. Marty would tally for both APR and MAY since his eff_dt is before MAY 2012 and his exp is within MAY 2012. etc..
    Based on the data below, the results should look like:
    APR MAY JUN
    4 3 2
    APR should have FRANK, MARK, MARTY, MARY,
    MAY should have FRANK, MARTY, MARY
    JUN should have FRANK and MARY
    NOAM and JEAN should not show up as their records with elg_code ' ' do not have eff_dt and exp_dt records that fall within APR-JUN 2012.
    So what I tried without success as it appears I have some kind of Cartesian issue (?), is:
    select count(m1.mbr_name) APR,
    count(m2.mbr_name) MAY,
    count(m3.mbr_name) JUN
    from mbr2 m1,
    mbr2 m2,
    mbr2 m3
    where m1.eff_dt < '01-may-2012'
    and m1.exp_dt > '01-apr-2012'
    and m1.elg_code = ' '
    and m2.eff_dt < '01-jun-2012'
    and m2.exp_dt > '01-may-2012'
    and m2.elg_code = ' '
    and m3.eff_dt < '01-jul-2012'
    and m3.exp_dt > '01-jun-2012'
    and m3.elg_code = ' '
    Below is the DML
    Thanks for any assistance!
    create table mbr2 (mbr_name varchar(10), grpid varchar(1), eff_dt date, exp_dt date, elg_code varchar(1))
    commit
    insert into mbr2 values ('MARK', 'A', to_date('01-01-2011', 'MM-DD-YYYY'), to_date('04-30-2012', 'MM-DD-YYYY'), ' ')
    insert into mbr2 values ('MARK', 'A', to_date('05-01-2012', 'MM-DD-YYYY'), to_date('12-31-2013', 'MM-DD-YYYY'), 'C')
    insert into mbr2 values ('MARTY', 'A', to_date('01-01-2011', 'MM-DD-YYYY'), to_date('05-31-2012', 'MM-DD-YYYY'), ' ')
    insert into mbr2 values ('MARTY', 'A', to_date('06-01-2012', 'MM-DD-YYYY'), to_date('12-31-2013', 'MM-DD-YYYY'), 'C')
    insert into mbr2 values ('FRANK', 'B', to_date('01-01-2011', 'MM-DD-YYYY'), to_date('06-30-2012', 'MM-DD-YYYY'), ' ')
    insert into mbr2 values ('FRANK', 'B', to_date('07-01-2012', 'MM-DD-YYYY'), to_date('12-31-2013', 'MM-DD-YYYY'), 'C')
    insert into mbr2 values ('MARY', 'B', to_date('01-01-2011', 'MM-DD-YYYY'), to_date('06-30-2012', 'MM-DD-YYYY'), ' ')
    insert into mbr2 values ('MARY', 'B', to_date('07-01-2012', 'MM-DD-YYYY'), to_date('12-31-2013', 'MM-DD-YYYY'), 'C')
    insert into mbr2 values ('JEAN', 'C', to_date('01-01-2011', 'MM-DD-YYYY'), to_date('07-01-2011', 'MM-DD-YYYY'), ' ')
    insert into mbr2 values ('JEAN', 'C', to_date('07-01-2011', 'MM-DD-YYYY'), to_date('01-01-2012', 'MM-DD-YYYY'), 'C')
    insert into mbr2 values ('NOAM', 'D', to_date('07-01-2012', 'MM-DD-YYYY'), to_date('12-31-2013', 'MM-DD-YYYY'), ' ')
    commit

    Hi,
    Here's one way:
    WITH     all_months     AS
         SELECT     LEVEL                         AS month_num
         ,     ADD_MONTHS (first_month, LEVEL - 1)     AS month_begin
         ,     ADD_MONTHS (first_month, LEVEL)           AS next_month_begin
         FROM     (
                   SELECT  TO_DATE ('04-01-2012', 'MM-DD-YYYY')     AS first_month
                   ,     TO_DATE ('06-01-2012', 'MM-DD-YYYY')     AS last_month
                   FROM     dual
         CONNECT BY     level     <= 1 + MONTHS_BETWEEN (last_month, first_month)
    SELECT    COUNT (CASE WHEN month_num = 1 THEN 1 END)     AS month_1
    ,       COUNT (CASE WHEN month_num = 2 THEN 1 END)     AS month_2
    ,       COUNT (CASE WHEN month_num = 3 THEN 1 END)     AS month_3
    FROM       all_months  a
    JOIN       mbr2        m  ON  a.month_begin       <= m.exp_dt
                            AND a.next_month_begin      >  m.eff_dt
    WHERE     m.elg_code      = ' '
    ;This assumes you know how many months will be in the output. If you want to derive that from the data, or to give the columns meaningful aliases (such as APR-2011 instead of MONTH_1), then you'll need dynamic SQL (to get separate columns for each month) or string aggregation (if you don't mind one big VARCHAR2 column, formatted to look like several columns). See {message:id=3527823}
    If you don't mind modifying the query a little every time you run it, you can hard-code the number of columns and the month names. In the main query, put exactly as many lines as you need, with the alias you want at the end. That is, instead of
    ,       COUNT (CASE WHEN month_num = 2 THEN 1 END)     AS month_2say
    ,       COUNT (CASE WHEN month_num = 2 THEN 1 END)     AS may_2012I'm not sure exactly what the problem was with the query you posted. It looks like this site cut off parts of the query.
    One thing that is definitely a mistake is that you're comparing DATE columns to VARCHAR2 literals. Never compare a DATE to a VARCHAR2; compare DATEs to DATEs (or compare VARCHAR2s to VARCHAR2s). So instead of
    and m1.exp_dt > '01-apr-2012'you should say
    and m1.exp_dt > TO_DATE ('01-apr-2012', 'dd-mon-yyyy')Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful.
    Edited by: Frank Kulash on Jun 26, 2012 3:32 PM

  • SQL distinct count

    Hi..
    Can anyone tell me how to do the SQL
    SELECT EMPNO,DISTINCT(COUNT(SALARY))
    FROM EMPLOYEE
    Thanks in Advnace......
    Rajeshwari

    You need to count the distinct account_keys in the account table as an in-line view and join that to the product table. Something like:
    SELECT p.product_key, p.name, a.cnt
    FROM product p,
         (SELECT product_key, COUNT(DISTINCT account_key) cnt
          FROM account
          GROUP BY product_key) a
    WHERE p.product_key = a.product_keyAlthough, your sample data gives odd results because there are two entries for p1 A and product p4 has two names D and B, although since it does not appear in accounts, it makes no differene in this particular case.
    If you actually want to show all of the products from the product table and a zero count if they do not appear in accounts, then you need an outer join, something like:
    SELECT p.product_key, p.name, NVL(a.cnt, 0) cnt
    FROM product p
    LEFT JOIN (SELECT product_key, COUNT(DISTINCT account_key) cnt
               FROM account
               GROUP BY product_key) a
       ON p.product_key = a.product_keyHTH
    John

  • How get Mailbox Folder Item Count for date range?

    How to make query to Exchange 2013 like this:
    query ItemCount (specified Mailbox, specified Folder (with subfolders), specified Date Range)?
    I find this script for Exchange 2010: http://gsexdev.blogspot.ru/2012/10/item-age-sample-one-reporting-on-item.html
    This script dont work for Exchange 2013 ((

    I believe you are making the change on both the places in code, as this path version would be different in 2013
    C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
    Cheers,
    Gulab Prasad
    Technology Consultant
    Blog:
    http://www.exchangeranger.com    Twitter:
      LinkedIn:
       Check out CodeTwo’s tools for Exchange admins
    Note: Posts are provided “AS IS” without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.

  • Count by date range

    Hi, I have data containing a task name and it's start and end date.
    Now, I want new data based on above that will tell how many tasks were running at any given date.
    Assuming that time stamp for each date is 00:00:00, and tasks start at Start_Dt but end just before End_dt (lower bound included, upper bound not)
    Input:
    Task     Start_Dt     End_D
    A    2013-12-01    2013-12-05
    B    2013-12-03    2013-12-04
    C    2013-12-03    2013-12-04
    D    2013-12-03    2013-12-06
    E    2013-12-04    2013-12-05
    F    2013-12-06    2013-12-07
    Output:
    Start   
    End     
    Count
    (Jobs)
    2013-12-01
    2013-12-03
    1
    (A)
    2013-12-03
    2013-12-04
    4
    (A,B,C,D)
    2013-12-04
    2013-12-05
    3
    (A,D,E)
    2013-12-05
    2013-12-06
    1
    (D)
    2013-12-06
    2013-12-07
    1
    (F)
    In the above, Task B should not be in 3rd row since it ended on 12/04 and hence not to be included in the 12/04 - 12/05 range (and B was not running in this period)
    alter session set nls_date_format = 'YYYY-MM-DD';
    select tmp.* from
    select 'A' TASK, to_date('2013-12-01','YYYY-MM-DD') START_DT, to_date('2013-12-05','YYYY-MM-DD') END_DT from dual
    union
    select 'B' TASK, to_date('2013-12-03','YYYY-MM-DD') START_DT, to_date('2013-12-04','YYYY-MM-DD') END_DT from dual
    union
    select 'C' TASK, to_date('2013-12-03','YYYY-MM-DD') START_DT, to_date('2013-12-04','YYYY-MM-DD') END_DT from dual
    union
    select 'D' TASK, to_date('2013-12-03','YYYY-MM-DD') START_DT, to_date('2013-12-06','YYYY-MM-DD') END_DT from dual
    union
    select 'E' TASK, to_date('2013-12-04','YYYY-MM-DD') START_DT, to_date('2013-12-05','YYYY-MM-DD') END_DT from dual
    union
    select 'F' TASK, to_date('2013-12-06','YYYY-MM-DD') START_DT, to_date('2013-12-07','YYYY-MM-DD') END_DT from dual
    )tmp
    order by 2,3
    How to write the sql on the input ('tmp' table)?
    Thanks,
    -srinivas y.
    Message was edited by: ysri
    Message was edited by: ysri. Updated tasks and dates.

    with
    data_table as
    (select 'A' task,date '2013-12-01' started,date '2013-12-05' ended from dual union all
    select 'B',date '2013-12-03',date '2013-12-04' from dual union all
    select 'C',date '2013-12-04',date '2013-12-05' from dual union all
    select 'D',date '2013-12-06',date '2013-12-07' from dual
    date_periods as
    (select date '2013-12-01' started,date '2013-12-03' ended from dual union all
    select date '2013-12-03',date '2013-12-04' from dual union all
    select date '2013-12-04',date '2013-12-05' from dual union all
    select date '2013-12-06',date '2013-12-07' from dual
    select to_char(p.started,'yyyy-mm-dd') "Start",
           to_char(p.ended,'yyyy-mm-dd') "End",
           count(*) "Count",
           '('||listagg(t.task,',') within group (order by t.task)||')' "(Jobs)"
      from date_periods p
           left outer join
           data_table t
        on greatest(t.started,p.started) < least(t.ended,p.ended)
    group by p.started,p.ended
    order by p.started
    Start
    End
    Count
    (Jobs)
    2013-12-01
    2013-12-03
    1
    (A)
    2013-12-03
    2013-12-04
    2
    (A,B)
    2013-12-04
    2013-12-05
    2
    (A,C)
    2013-12-06
    2013-12-07
    1
    (D)
    Regards
    Etbin

  • Oracle SQl query to find date range based on another cloumn value

    Hi Folks,
    I want to extract records for the employees who have consecutive vacation/leave from a table. If an emp has vacation of 3 days (MON-WED), the table contains 3 distinct records for him,
    e.g. My table contains records as shown below.
    EmpName Paycode ApplyDate Amt. of Hrs
    emp1 vacation 5/1/2010 8
    emp1 vacation 5/2/2010 8
    emp1 vacation 5/3/2010 8
    I am trying to get the output like this...
    Emp Name Paycode Leave Start Date Leave End Date TotalHrs
    emp1 vacation 5/1/2010 5/3/2010 24
    Note: If the smae emp has sets of vacation in another month, that should come as a separate record with start date and end date(last date of vacation for that set).
    I have a query which does not return any rows. Any help to repair this query or any better one would be of great help.
    ==================================================================
    WITH vpt AS (
    select personnum as empname, paycodename as paycode, applydate, timeinseconds/3600 as numhours from VP_TOTALS
    where applydate between to_date('05/01/2010','MM/DD/YYYY') AND to_date('12/31/2010','MM/DD/YYYY')
    AND paycodename in ('US-Vacation','US-Bereavement','US-Sick','US-Jury Duty')
    select
    empname,
    paycode,
    min(applydate) as startdate,
    max(applydate) as enddate,
    sum(numhours) as totalhours
    from (
    select
    empname,
    paycode,
    applydate,
    numhours,
    -- number the blocks sequentially
    sum(is_block_start) over (partition by empname, paycode order by applydate) as block_num
    from (
    select
    empname,
    paycode,
    applydate,
    numhours,
    -- Mark the start of each block
    case
    when applydate = prev_applydate + 1 then 0 else 1 end as is_block_start
    from (
    select
    empname,
    paycode,
    applydate,
    numhours,
    lag (applydate) over (partition by empname, paycode order by applydate) prev_applydate
    from vpt
    group by empname, paycode, block_num
    ===================================================================
    Thanks,
    Maha

    Hi Dear,
    Can I do reverse I mean I can get output as your question from your output as below:
    I have this table
    FID      STARTD ATE END DATE
    1 01-MAY-10 03-MAY-10
    1 09-MAY-10 11-MAY-10
    1 03-JUN-10 04-JUN-10
    2 03-JUN-10 04-JUN-10
    2 04-AUG-10 04-AUG-10
    2 06-AUG-10 06-AUG-10
    I want like this.
    FID FDATE
    1 01-MAY-10
    1 02-MAY-10
    1 03-MAY-10
    1 09-MAY-10
    1 10-MAY-10
    1 11-MAY-10
    1 03-JUN-10
    1 04-JUN-10
    2 03-JUN-10
    2 04-JUN-10
    2 04-AUG-10
    2 06-AUG-10
    And:
    How can i get date wise entry from Joining date to relieving date like..
    FID      START DATE END DATE
    1 01-MAY-10 03-MAY-12
    1 09-MAY-10 11-MAY-11
    2 04-AUG-10 04-AUG-11
    I want like this.
    FID FDATE
    1 01-MAY-10
    1 03-MAY-10
    1 04-MAY-10
    1 05-MAY-10
    1 16-MAY-10
    1 17-MAY-10
    1 08-May-10
    1 09-May-10
    1 03-May-12
    Can you please help me.
    Thanks,
    Edited by: 978452 on Dec 24, 2012 12:02 AM

  • Get the SQLs In between a date range

    Get the SQLs irrespective of sessions in the order of its execution from a specified schema with in a date time range

    Which version of Oracle are you using?
    Jaffar

  • SQL Query to get Date Range Values

    Hi,
    The database is Oracle11i.
    I am looking for a way to generate list of dates from a fixed date in the past (could be hardcoded) to current day (sysdate).
    That is, if the fixed date is 19 June 2011 and assuming that today is 24 June 2011 the SQL should be able to generate the
    following:-
    19-June-2011
    20-June-2011
    21-June-2011
    22-June-2011
    23-June-2011
    24-June-2011
    And the constraint is that I can't make any change to the database in question. I can only fire an SQL query (SELECT). No
    usage of time dimension kind of approach (time dimension is not available here) and no procedures, PL/SQL etc. Is there any way?
    Thanks

    Jaimeen Shah wrote:
    Hi,
    The database is Oracle11i.
    I am looking for a way to generate list of dates from a fixed date in the past (could be hardcoded) to current day (sysdate).
    That is, if the fixed date is 19 June 2011 and assuming that today is 24 June 2011 the SQL should be able to generate the
    following:-
    19-June-2011
    20-June-2011
    21-June-2011
    22-June-2011
    23-June-2011
    24-June-2011
    And the constraint is that I can't make any change to the database in question. I can only fire an SQL query (SELECT). No
    usage of time dimension kind of approach (time dimension is not available here) and no procedures, PL/SQL etc. Is there any way?
    Thanks
    SQL> def date_start = '13/11/2010'
    SQL> def date_end   = '22/11/2010'
    SQL> with
      2    data as (
      3      select to_date('&date_start', 'DD/MM/YYYY') date1,
      4             to_date('&date_end',   'DD/MM/YYYY') date2
      5      from dual
      6    )
      7  select to_char(date1+level-1, 'DD/MM/YYYY') the_date
      8  from data
      9  connect by level <= date2-date1+1
    10  /
    THE_DATE
    13/11/2010
    14/11/2010
    15/11/2010
    16/11/2010
    17/11/2010
    18/11/2010
    19/11/2010
    20/11/2010
    21/11/2010
    22/11/2010

  • SQL Syntax for hour/date range in Query

    Hi
    I am trying to set up an query for sales order documents procesed in the last 30 minutes to be set as an alert to be run every 30 minutes to the sales manager.  I am having difficulty getting the syntax for the last 30 minutes
    Any suggestions?
    David

    hi,
    I'm not sure query is correct,but u can modify it futher to get correct one.
    SELECT T0.DocNum, T0.DocDate, T0.CardName, T0.DocTotal FROM ORDR T0 WHERE DateDiff(dd, T0.DocDate ,getdate()) = 0 and
    DateDiff(Minute,T0.DocTime,' ') <= 30
    Jeyakanthan

  • How to get a date range in JDBC sql

    I am using the following in my sql to get a date range... but what if the field is a timestamp will that still work or not...
    AND a.date>=? AND a.date<=?

    Suzie,
    No offence, but is there something stopping you from testing it yourself?
    Good Luck,
    Avi.

  • Distinct Count Calculation

    Hello everybody,
    I have a cube with appointments including dimensions for companies and dates.
    One of my measures is "Appointments" which is the count of all appointments. Another calculated member is "Visits" which is the count of appointments with the type of "Visits".
    This is my MDX epxression for "Visits":
    AGGREGATE([Appointment].[Type].&[Visit], [Measures].[Appointments])
    Now I would like to create a new calculated member "Company Visits" which should be the distinct count of "Visits" by company and date.
    Example: 2 "Visits" in one company on the same day should be 1 "Company Visit"
    In T-SQL this query works:
    COUNT(
    DISTINCT(
    CASE [Type]
    WHEN "Visit" THEN CAST([CompanyID] AS NVARCHAR) + CONVERT(NCHAR(8), CAST([Date] AS NVARCHAR))
    ELSE NULL
    END
    ) AS [Company Visits]
    How can I do this with MDX in calculations?
    Additionally I would like to have a calculated member "Days in Field" as distinct count of dates with "Visits".
    Thanks in advance and best regards
    Lars

    Hi Lars,
    Based on your description, you want to create a new calculated member to calculate the distinct count of "Visit" for each company, right? In this case, you can use DistinctCount to achieve your requirement, here is a sample query about DistinctCount function
    for your reqerence.
    with member [DistCount] as
    distinctcount(exists(Employee.Employee.children,,"Reseller Orders"))
    Select {[Measures].[Reseller Order Count],
    [Measures].[DistCount]} on 0,
    ([Employee].[Gender].children) on 1
    From [AdventureWorks]
    Reference:DistinctCount (MDX)
    Regards,
    Charlie Liao
    TechNet Community Support

  • Extracting a count of distinct values between two date ranges over months

    Hi All,
    I am having a bit of difficulty in figuring out the query to build a list of active campaigns over a date range.
    i.e. I have a table with campaign IDs and their start and end date details like this
    Campaign_id     Start_date     End_date
            10001     1-Jun-09     31-May-11
            10002     1-Jun-09     23-Jun-11
            30041     21-Aug-09     31-Dec-09
            20005     3-Jun-10     31-May-11
            90021     21-Nov-09     30-Nov-10
            54000     1-Jun-11     1-Dec-12
            35600     1-Mar-10     31-Mar-12 What the above data means is, for eg. the campaign 10001 is active from 1-Jun-09 to 31-May-11 i.e. for 24 months (inclusive of the month Jun-09 and May-11)
    What I need to figure out is the counts of active campaigns between a date range and display that active count at a month level (for e.g. lets say we want to see all the campaigns that were active
    between the date range '01-JUN-2007' and '30-APR-2012' ). So the partial output would be as seen below. The list would continue till december-2012
    Month    Year    Count of active campaigns
    Jan    2009    0
    Feb    2009    0
    Mar    2009    0
    Apr    2009    0
    May    2009    0
    Jun    2009    2
    Jul    2009    2
    Aug    2009    3
    Sep    2009    3
    Oct    2009    3
    Nov    2009    4
    Dec    2009    4
    Jan    2010    3
    Feb    2010    3
    Mar    2010    4
    Apr    2010    4
    Dec    2012    1 Could anybody please help me with the right query for this.
    Thanks a lot for help
    Regards
    Goldi

    set pagesize 40
    with tab as
                    select 1 id, sysdate -100 start_date, sysdate end_date from dual
                    union
                    select 1 id, sysdate -200 start_date, sysdate -150 end_date from dual
                    union
                    select 1 id, sysdate -600 start_date, sysdate - 400 end_date from dual
                    union
                    select 1 id, sysdate -300 start_date, sysdate - 150 end_date from dual
                    union
                    select 2 id, sysdate -100 start_date, sysdate-50 end_date from dual
          year_tab as
                        select
                                 add_months(min_date, level -1) m
                        from
                                select min(trunc(start_date,'YYYY')) min_date, add_months(max(trunc(end_date,'YYYY')), 12) max_date
                                from tab
                        connect by level <= months_between(max_date, min_date)
    select to_char(m,'YYYY') year_,
             to_char(m,'Month') month_,
             nvl(act, 0) act
    from   year_tab,
                select m date_,count(*)  act
                from tab, year_tab
                where m between trunc(start_date,'MM') and trunc(end_date,'MM')
                group by m
                ) month_tab
    where m = date_(+)
    order by m;
    YEAR_ MONTH_           ACT
    2010  January            0
    2010  February           0
    2010  March              0
    2010  April              0
    2010  May                0
    2010  June               0
    2010  July               0
    2010  August             0
    2010  September          1
    2010  October            1
    2010  November           1
    2010  December           1
    2011  January            1
    2011  February           1
    2011  March              1
    2011  April              0
    2011  May                0
    2011  June               0
    2011  July               1
    2011  August             1
    2011  September          1
    2011  October            2
    2011  November           2
    2011  December           2
    2012  January            2
    2012  February           2
    2012  March              2
    2012  April              1
    2012  May                1
    2012  June               0
    2012  July               0
    2012  August             0
    2012  September          0
    2012  October            0
    2012  November           0
    2012  December           0
    36 rows selected.

  • All months in date range plus running count

    Oracle 11g
    Hello all,
    Having trouble getting the following query to return proper results. Have a table with a MEMBERNO, BUSINESS_LINE, ELIGIBILITY_START_DATE, ELIGIBILITY_END_DATE.
    MEMBERNO is not unique
    BUSINESS_LINE is not either
    Start and end date are periods of time where: MEMBERNO&BUSINESS_LINE have changed
    I need to list the member number, business_line, and each month that falls within the date range beginning with eligibility_start_date & eligibility_end_date, as well as a running count of the total in that span.
    Eg.
    member, business_line, month, year, count
    1234, bus1, 01, 2001, 1
    1234, bus1, 02, 2001, 2
    1234, bus1, 03, 2001, 3
    Here is my SQL, it is not sequencing the months dates correctly and I can not figure out why. Any help is very appreciated:
    SELECT memberno,
    business_line,
    TO_CHAR (ADD_MONTHS (start_date, LEVEL - 1), 'MM') as MONTH,
    TO_CHAR (ADD_MONTHS (start_date, LEVEL - 1), 'YYYY') as YEAR,
    ROW_NUMBER () OVER (PARTITION BY key1 ORDER BY start_date ASC) as MEMBER_MONTH_COUNT
    FROM (SELECT memberno,
    business_line,
    eligibility_start_date as start_date,
    eligibility_end_date as end_date,
    member_nbr || business_line as key1
    FROM eligibility)
    CONNECT BY LEVEL <=
    MONTHS_BETWEEN (TRUNC (END_DATE, 'MM'),
    TRUNC (START_date, 'MM'))
    + 1;
    Edited by: 935047 on Jul 25, 2012 5:58 AM
    Edited by: 935047 on Jul 25, 2012 6:18 AM

    935047 wrote:
    I need to list the member number, business_line, and each month that falls within the date range beginning with eligibility_start_date & eligibility_end_date, as well as a running count of the total in that span.
    Eg.
    member, business_line, month, year, count
    1234, bus1, 01, 2001, 1
    1234, bus1, 02, 2001, 2
    1234, bus1, 03, 2001, 3I could not understand what the Running Count mean. Hence, I used Row_Number (Same as you did).
    Below query might match yours.
    with data (memb_no, bus_line, st_date, end_date) as
      select 1234, 'bus1', to_date('01-01-2001', 'MM-DD-YYYY'), to_date('06-30-2001', 'MM-DD-YYYY') from dual
      union all
      select 1234, 'bus1', to_date('07-01-2001', 'MM-DD-YYYY'), to_date('07-30-2002', 'MM-DD-YYYY') from dual
    min_max as
      select memb_no, bus_line, min(st_date) st_date, max(end_date) end_date
        from data
       group by memb_no, bus_line
    lvl as
      select level l
        from dual
      connect by level <= (select max(round(months_between(end_date, st_date))) from min_max)
    select memb_no,
           bus_line,
           to_char(add_months(st_date, l - 1), 'MM') months,
           to_char(add_months(st_date, l - 1), 'YYYY') Year,
           row_number() over (partition by memb_no, bus_line order by st_date) cnt
      from min_max cross join lvl
    order by year, months;
    ----OUTPUT------------------------
    MEMB_NO BUS_LINE MONTHS YEAR CNT
       1234 bus1     01     2001   1
       1234 bus1     02     2001  19
       1234 bus1     03     2001   3
       1234 bus1     04     2001   4
       1234 bus1     05     2001   5
       1234 bus1     06     2001   6
       1234 bus1     07     2001   7
       1234 bus1     08     2001   8
       1234 bus1     09     2001   9
       1234 bus1     10     2001  10
       1234 bus1     11     2001  11
       1234 bus1     12     2001  12
       1234 bus1     01     2002  13
       1234 bus1     02     2002  14
       1234 bus1     03     2002  15
       1234 bus1     04     2002  16
       1234 bus1     05     2002  17
       1234 bus1     06     2002  18
       1234 bus1     07     2002   2
    19 rows selected

  • 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

  • ADGENDBC.SH가 FND_APPLICATION_SERVERS에 UPDATE안 하는경우

    제품 : AOL 작성날짜 : 2004-05-19 ADGENDBC.SH가 FND_APPLICATION_SERVERS에 UPDATE안 하는경우 ================================================== PURPOSE adgendbc.sh가 돌아갈때 fnd_application_servers 에 row를 생성하는데 11.5.8 부터는 record가 생기지 않는 이유를 설명하고 있다. Explanation 11.5.8부

  • QS1 MasterCard to QS MasterCard product change approved! Follow up questions for all.

    My co-worker called in and requested a product change from QS1 to QS MasterCard with no annual fee after having the card for little over a month. My question is will the refund a portion of the annual fee and do you think they will make this card a W

  • Start new session automatically after the current one is expired

    Hi Guys, My application should be displayed on the screen 24/7 . The information there is being refreshed every 5 minutes. When the APEX session is expired the refresh stops working and the page has to be reloaded. I'm looking for the solution that w

  • My problem is to synchronize Lightroom 4 with Elements 11.

    I have another computer with Lightroom 4 and Elements 10 and there is no problems to operate from Lightroom to Elements. I have tried almost everything and spent several hours to find a solution. My both computers are new HP Pavillion and have Window

  • Itunes won't start in windows 8

    Itunes will load, but the store will not load from the Itunes 'button'. I've relloaded iTunes, with no change. HELP!!!