Group by week

Hi,
I need to build a SQL Query that group data by week.
for example :
table looks like this
the_date the_qty
6/5/2002 1
6/10/2002 4
6/14/2002 5
6/15/2002 36
6/19/2002 76
6/20/2002 88
6/21/2002 88
6/22/2002 24
6/24/2002 53
6/25/2002 281
6/28/2002 2
6/30/2002 3
desired result
6/9/2002 1
6/16/2002 41
6/23/2002 276
6/30/2002 336
7/7/2002 3
thanks
regards
sunil

Hi,
use
group by next_day(trunc(date_column-1),'SUNDAY')
Best,
EAThis is not correct.
SELECT
     next_day(trunc(the_date-1),'SUNDAY')     the_date,
     SUM(the_qty)               the_qty
FROM
     t
GROUP BY
     next_day(trunc(the_date-1),'SUNDAY')
THE_DATE        THE_QTY
06/09/2002            1
06/16/2002           45
06/23/2002          276
06/30/2002          339
... or group by trunc(yourdate,'W')trunc(yourdate,'W') will not produce the desired result in this case.
SELECT
     TRUNC(the_date, 'W')     the_date,
     SUM(the_qty)          the_qty
FROM
     t
GROUP BY
     TRUNC(the_date, 'W')
THE_DATE        THE_QTY
06/01/2002            1
06/08/2002            9
06/15/2002          288
06/22/2002          360
06/29/2002            3

Similar Messages

  • Group by week between date range

    Hi,
    i'm having a table for documents. The documents are received from diffeent dates. I've to calculate number of documents received on weekly basis.
    I need an sql to count the number of documents between two given dates grouping by weekly.
    My week starts on Sunday and ends with Saturday.
    I've tried group by with to_char(documentdate,'IW') , but this will take Monday to Sunday as a week & the incomlete weeks i'm not able to calculate. ie : in the below output the date range 1/28/2007 - 1/31/2007 is not a complete week . ( ie saturday to wednesday)
    I need out put should be like this for Date Range: 12/31/2006 to 1/31/2007
    week               count of documents
    12/31/2006 - 1/6/2007 10
    1/7/2007 - 1/13/2007     40
    1/14/2007 - 1/20/2007     30
    1/21/2007 - 1/27/2007     20
    1/28/2007 - 1/31/2007 10
    Please help me to get this.....
    (columns in documents table is documentid and documentdate)

    your're very close with IW. you just need to shift the data to get it to fall within the correct range. btw, you don't need julian dates. it's overkill
    trunc(date+1,'IW') will push the date into the correct week range (IW will put sunday one week earlier than you want, so push it ahead a day before truncating).
    then subtract 1 day from the result to get it to display with sunday's date instead of monday
    trunc(mydate+1, 'IW')-1
    and the week end date is simply trunc(mydate+1, 'IW')_5
    select mydate, to_char(mydate,'Dy') dy,
    trunc(mydate+1,'IW')-1 wk_Start,
    trunc(mydate+1,'IW')+5 wk_end
    from (select sysdate-rownum mydate from dual connect by level < 20)
    order by 1

  • Grouping Data Weekly

    Hi,
    I have a query in sql
    Table employees
    columns : empid,hiredate,job_id,salary
    I want to count(empid) and group data weekly with job_id , order by month.
    Sample of Data like :
    mon week job_id count(empid)
    jan week1 sa_rep 15
    jan week2 sa_rep 20
    jan week3 sa_rep 35
    jan week4 sa_rep 40
    feb week1 sa_rep 10
    feb week2 sa_rep 05
    feb week3 sa_rep 12
    feb week4 sa_rep 15
    Help please
    Thanks and Regards,
    Ramesh J C

    you can
    group by to_char(hiredate, 'IW'),  --week of year
                  to_char(hiredate, 'Month')and
    order by to_char(hiredate, 'Month')

  • Grouping Via Week Ending Date

    Hi All,
    I have transaction line data for each day for our customer and i would like to group via Week Ending date.  Our week runs from Sunday to Saturday.
    If i Add the transaction date to the group expert it allows me to group via week(perfect) but does it via week commencing.  I see you can group via formula, does any one know how you can get the grouping via Week Ending.
    thanks for any help and advise.
    mike

    Try using this formula...
    DateAdd("ww", DateDiff("ww", #1/6/1900#, {TableName.DateField}), #1/6/1900#)
    This formula will calculate the "Following Saturday" for any given date. If the date supplied is a Saturday, it will return that same date.
    So...
    11/2/2010 &gt; 11/6/2010
    11/13/2010 &gt; 11/13/2010
    11/14/2010 &gt; 11/20/2010
    HTH,
    Jason

  • Capacity requirement group by week

    Inside CM01, given a work center,  we can get capacity requirements group by weeks.
    Is there any function module to get the same answer?
    I've found that table KBED seems to hold the information I need.
    But don't know how to group the records into different slot of week.
    Can anybody help?
    Regards,
    Norman.

    Hi,
    user588757 wrote:
    Hi Frank,
    Too good... it worked !!!!!!!!!!!!Thanks. If it's too good, I suppose you can always add errors.
    And can we give input for END DATE...it does have only start date..Yes, you could give the end date instead of the start date.
    You could allow either.
    Suppose you had a form that returned user_input_date (a DATE) and a string, user_date_type, returned by a radio group, 'START' if the user indicated that the date entered was a start date, or 'END' otherwise.
    WITH  d  AS
        SELECT  user_input_date -     CASE
                             WHEN  user_date_type = 'START'
                             THEN  0
                             ELSE  6
                        END     AS input_startdate
    ,     g  AS
        SELECT  (creation_date - input_startdate)  AS wk_num
        FROM    xxsirf_per_addresses_tl
        CROSS JOIN  d
    SELECT    MAX (input_startdate + (7 * wk_num))          AS wk_start
    ,         MAX (input_startdate + (7 * wk_num) + 6)     AS wk_end
    ,         COUNT (*)
    FROM      g
    GROUP BY  wk_num
    ORDER BY  wk_num;Though if you were running this from a form, it would be easy to do sub-query d separately, and pass the input_startdate that it computed to the query I posted earlier.
    I would discourage allowing users to input both start- and end dates, because they won't necessarily be six days apart.
    Of course, you could ignore one if both were entered, but that's exactly the kind of thing that confuses end users.

  • BSIS - GROUP By Week Across Columns

    I am new to ABAP Query...Using SQ01 to create a query of BSIS table.
    I ultimately want to pull all cost center (KOSTL), account (HKONT) combinations in Local Currency (DMBTR) and GROUP the data by week based on posting date (BUDAT).  I want the weeks as columns in the query.
    Report...                  Week 1          Week 2         Week 3         Week 4
    KOSTL, HKONT          XX                    XX                 XX                XX
    Can anyone please help me with how to make this happen.  Do I need to use ABAP code?
    Thanks

    that's not possible without abap coding - better write an abap-report:
    - that's your internal table:
    begin of itab..
          hkont,
          kostl,
          week,
          wrbtr,...
    -use fm DATE_GET_WEEK to convert BUDAT into week.-no.
    hope that helps
    A.

  • Grouping by week using Date column

    I have a table with a date column. I'd like to generate a report grouping all entries by week. Is this possible with the date expressions/functions within Oracle?
    Thanks

    What is your definition of a week?
    select to_char(sysdate, 'IW') from dual
    will return 21 which is the week of the year according to the ISO standard
    So a query such as
    SELECT TO_CHAR(mydate, 'IW'), col1, col2
    FROM mytable
    GROUP BY TO_CHAR(mydate, 'IW')
    will group the data by the ISO week.
    You may also want to select the year as part of the query.
    null

  • Group a week data in a few subgroup

    Hi,
    I have a special requirement that I would like to do it using SQL. Suppose I have the following table:
    Day    Count
    1        5
    2        15
    3        10
    4        31
    5        25
    6        2
    7        5
    ------------------------I would like to group the above table into 3 subgroup (as shown by the dotted lines). As you may have realised, the grouping condition is "Start from Day1 until Day7 (end of week). If a day count is more than 30, make a subgroup. If less than 30, go to next day until cumulative count is more than 30. When cumulative count is 30, make a new subgroup and reset cumulative count to zero for the next day. Algorithm continues until end of the week.
    Thanks.

    It is not for any frontend...
    It is actually for statistical calculations.(some folks in my dept pointed out that for meaningful statistic, the sample size should be more than 30..its their rule)
    So the final result based on the tables I have shown is:
    Set  Count   
    1      30
    2      31
    3      32

  • Group by week on select statement

    Hi friends,
    I have a select statement which returns me the data that i need to group it on a weekly basis. The week starts from wednesday morning to tuesday night. what should e the syntax for group by clause to get the desired result. I am using the bar chart to display the results.
    Please let me know.
    Regards,
    Pradeep

    I have moved this question to SQL/PLSQL forum.

  • Group by Week and then by Month

    Hello Forum Members,
    Can you please help me on this:
    City      Demand Demand_Date
    Seattle    20     06/04/2014
    Seattle    10     06/07/2014
    Seattle    30     06/16/2014
    Seattle    20     07/04/2014
    Austin    10     06/07/2014
    Austin    30     06/16/2014  
    City       Demand           Demand_Week      Demand_by__Month  Demand_Month
    Seattle     30              06/07/2014
    Seattle     30              06/21/2014         60               
    06/2014
    Seattle     20              07/05/2014         20
    Austin      10              06/07/2014
    Austin      30              06/21/2014         40               
    07/2014
    Best,
    Sqlquery9

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Now we have to guess because you are rude. 
    Learn how to follow ISO-11179 data element naming conventions and formatting rules. Have no idea what this is. Temporal data should use ISO-8601 formats. You failed! 
    Code should be in Standard SQL as much as possible and not local dialect. You did not even try! Are you always this rude to people that you want to do your job for you? 
    This is minimal polite behavior on SQL forums. Here is my guess at cleaning up your mess. 
    CREATE TABLE Cocaine_Demand
    (city_name VARCHAR(15) NOT NULL,
     demand_date DATE DEFAULT CURRENT_TIMESTAMP NOT NULL,
     PRIMARY KEY (city_name, demand_date),
     demand_cnt INTEGER NOT NULL);
    INSERT INTO Cocaine_Demand
    VALUES
    ('Seattle', '2014-06-04', 20),
    ('Seattle', '2014-06-07', 10),
    ('Seattle', '2014-06-16', 30),
    ('Seattle', '2014-07-04', 20),
    ('Austin', '2014-06-07', 10),
    ('Austin', '2014-06-16', 30); 
    Report Period Table
    Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML.
    The report period table gives a name to a range of dates that is common to the entire enterprise. 
    CREATE TABLE Something_Report_Periods
    (something_report_name CHAR(10) NOT NULL PRIMARY KEY
       CHECK (something_report_name LIKE <pattern>),
     something_report_start_date DATE NOT NULL,
     something_report_end_date DATE NOT NULL,
      CONSTRAINT date_ordering
        CHECK (something_report_start_date <= something_report_end_date),
    etc);
    These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
    data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00'
    Weeks within Year: 
    I would build a calendar table with a ISO-8601 week-within-year format column in addition to the usual Common Era date. This format is 'yyyyWww-d' where yyyy is the year, W is a separator token, ww is (01-53) week number and d is (1-7) day of the week.
    You input any calendar date, find the week-within-year column and return the dates that match on a LIKE predicate.
    WHERE sale_day LIKE '2012W26-[67]'
    There are several websites with calendars you can cut & paste, but you can start your search with: http://www.calendar-365.com/week-number.html 
    Try to write this yourself. If you were too lazy to post DDL or DML, why should we do it for you? 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Group by Month then week !!!

    Hey All,
    I would like to group by month of a year and then group by weeks and display the values for the weeks.
    For example: In the year 2008,January . The table should have (January,2008) in the first row and then (week 1 ,week 2 ,week 3 , week 4 and week 5 )
    in the second row . followed by the pertaining values for those weeks.
    Project ID----|----------------------January,2008------------------------|-----
    ----------------|Week 1 | Week 2 | Week 3 | Week 4 | Week 5 |-----
    xx34----------|---- 1--- |---- 2 ---|---- 1 ---|---- 1 ---|---- 1 ---|-----
    It would great if anybody could help me in resolving this usse either through XML Publisher or through SQL coding.
    Thank u all...

    Hey All,
    I would like to group by month of a year and then group by weeks and display the values for the weeks.
    For example: In the year 2008,January . The table should have (January,2008) in the first row and then (week 1 ,week 2 ,week 3 , week 4 and week 5 )
    in the second row . followed by the pertaining values for those weeks.
    Project ID----|----------------------January,2008------------------------|-----
    ----------------|Week 1 | Week 2 | Week 3 | Week 4 | Week 5 |-----
    xx34----------|---- 1--- |---- 2 ---|---- 1 ---|---- 1 ---|---- 1 ---|-----
    It would great if anybody could help me in resolving this usse either through XML Publisher or through SQL coding.
    Thank u all...

  • Group by date and print for every week

    Crystal defaults to using Sunday-Saturday as its weekly breakdown when grouping.  I need to group by week but need to show a Monday-Saturday week.  Any help will be appreciated.
    Thanks,
    John

    I figured it out. I grouped on a formula containing:
    datediff("ww",date(year(currentdate),1,1),{PR_GLDET.Pay_Date},crMonday)

  • Grouping Weeks in Numbers

    Hi Guys, I'd really appreciate your help.
    I'm creating a spreadsheet which will simply record my business sales with dates, invoices numbers and the amount taken in.
    I want to create a graph that will group together my WEEKLY sales. The problem is I can't find any way to group the weeks together? Does anyone have any good ideas for me?
    Thanks alot. Dan.

    Make another column that has the division to figure out what week that row belongs to. A summary table to sum/count/whatever by each week as its row header. Graph off of that. Its basically the manual way of creating a small pivot table from excel.
    Hope that helps some,
    Jason

  • How to create a sum on change of a detailed record without using groups

    Hi,
    I'm working on an overtime/payroll report.  Overtime hours are calculated based on hours worked greater than 40 within the span of Sunday to Saturday.  Further, pay periods are every two weeks and do not align with the calendar week of sunday to saturday.
    I've managed to figure out how to do the overtime calculation from sunday to saturday and then the totals for each of these calendar weeks. However, I'd also like to calculate the totals for the pay periods.  I cannot group on both the calendar week AND the pay period id because sometimes the calendar week starts before the pay period starts and sometimes the pay period starts before the calendar week. So, one is not a sub-group of the other.  I tried setting both up as groups but it, unfortunately, resets by hour calculations at the wrong point because when one group is still going the other is ending.
    So, the report is working well with just the one group - calendar week (oh, and there is a higher level group - employee id as this calculation is done for each employee). I can include the pay period id in the detail lines and I can see when it changes. So, if I could create a formula that summed the hours by pay period id and than reset when a new pay period id begins that is what I am after. I just want the sum of hours upon each change of pay period id.  I'll attempt to show what the data looks like below:
    Group 1: Employee Name (say Fred Jones)
       Group 2: Week Beginning January 8, 2012
    Date  RegularHours   OvertimeHours  PayPeriodId
    Jan 8        12                              0                            1
    Jan 9        12                              0                            1
    Jan 10      12                              0                            1
    Jan 11       4                               8                            1
    Jan 12       0                               12                          1
    Jan 13       0                               9                            1
    Jan 14       0                               6                            1
    Total      40                          35                   
    Group 2: Week Beginning January 15, 2012
    Date  RegularHours   OvertimeHours  PayPeriodId
    Jan 15      12                              0                            1
    Jan 16      12                              0                            1
    Jan 17      12                              0                            1
    Jan 18       4                               9                            2
    Jan 19       0                               10                          2
    Jan 20       0                               8                            2
    Jan 21       0                               7                            2
    Total      40                          34                   
    So, the total hours for pay period #1 should be:
    RegularHours   OvertimeHours
    76                                35
    And, the total hours for pay period #2 should be:
    RegularHours   OvertimeHours
    4                                   34
    I tried creating a formula: Distinctcount ({@OT Hours}, {Command.pay_periods_id}) but Crystal says I cannot summarize the formula that is in it.
    I'm not a programmer but it feels like a loop of some sort (For each, unique pay period id sum the OT Hours).
    Any and all help much appreciated in advance!
    Mark
    Edited by: mahewitt on Feb 14, 2012 4:42 AM

    Hi Mark,
    Here's something I have come up with:
    1) Create this formula and place it on the details section beside the PayPeriodID field.Replace in the formula with PayPeriodId, with RegularHours and with OvertimeHours.
    WhilePrintingRecords;
    numbervar array reg_hrs;
    numbervar array ot_hrs;
    numbervar array payid;
    numbervar reg;
    numbervar ot;
    numbervar x;
    numbervar y;
    if not({PayperId} in payid) then
        y := y + 1;
        redim preserve payid[y];
        payid[y] := {PayperId};
    if onlastrecord then
        reg := reg + {Regular};
        ot := ot + {Overtime};
        x := x + 1;
        redim preserve reg_hrs[x];
        redim preserve ot_hrs[x];
        reg_hrs[x] := reg;
        ot_hrs[x] := ot;
    else if {PayperId} = next({PayperId}) then
        reg := reg + {Regular};
        ot := ot + {Overtime};
    else
        reg := reg + {Regular};
        ot := ot + {Overtime};
        x := x + 1;
        redim preserve reg_hrs[x];
        redim preserve ot_hrs[x];
        reg_hrs[x] := reg;
        ot_hrs[x] := ot;
        reg := 0;
        ot := 0;
    2) Create this formula and place it on the Group Footer 1 (Employee Name group):
    WhilePrintingRecords;
    numbervar array payid;
    numbervar array reg_hrs;
    numbervar array ot_hrs;
    numbervar i;
    stringvar final;
    for i := 1 to ubound(payid) do
        final := final + "For Pay Period # "&payid<i>&chr(13)&chr(13)&"Regular Working Hours are :"&reg_hrs<i>&chr(13)&"Overtime Hours are :"&ot_hrs<i>&chr(13)&chr(13)&chr(13)
    final;
    3) Right-click this field and select Format Field > Common tab > Check the 'can grow' option and increase the horizontal size of the formula field to around 3.5 to 4'
    4) Create this formula to reset the variables at the Group Header 1. This will make sure it prints the Regular and Overtime hours for every employee:
    whileprintingrecords;
    numbervar array reg_hrs := 0;
    numbervar array ot_hrs := 0;
    numbervar array payid := 0;
    numbervar reg := 0;
    numbervar ot := 0;
    numbervar x := 0;
    numbervar y := 0;
    numbervar i := 0;
    stringvar final := "";
    You may then hide the 1st and the last formula (Right-click > Format field > Common tab > Suppress)
    Let me know how this goes!
    -Abhilash

  • SSRS show trend chart over column chart per series groups

    Need help in designing following report in SSRS, where I have a chart report with 2 category grouping fields and 1 series group field (as with category grouping, the reason being, i need to show columns in group of 4 joined together based on their grouping
    on top) .
    Below are my queries
    1. how to show my category grouping values on top of chart (showing group in different color) and series grouping values on bottom of chart (under each bar)
    2. I need to show trend line over each series group data.
    For example, First category group is over hotel name, second category group is over room type (deluxe, executive & suite) and one Series group over week number (for a month report), and the chart value is total occupancy (per hotel per room type per week
    number). Now for point 1, Hotel name and room type needs to be on top of the column (total occupancy) chart, where a week iteration number (1,2,3,4 for a month) at the bottom of the chart under every column.
    And for point 2, I need to show trend line per room per week occupancy was improved or not.
    Regards, Sujay

    Hi Sujay,
    According to your description, you want to display the two category group values at the top of the total occupancy value. Also you want to create a trend line over series values.
    For your first requirement, you can specify the Label data as a combination of two category group values and total occupancy values. Then change the location of series group value legend. Please refer to below screenshot.
    For your second requirement, you can add additional total occupancy values to the Chart Data panel, then change the chart type as Smooth Line.
    If you have any question, please feel free to ask.
    Best regards,
    Qiuyun Yu
    Qiuyun Yu
    TechNet Community Support

Maybe you are looking for

  • Photoshop Elements 8 Editor

    I keep getting an error that my editor software has stopped working. It was working just fine till about 3 days ago. Using Windows Vista, IE8, Office 2007 The organizer still works. My Premiere Elements 8 is still working. Here is what I've tried so

  • Understanding Camera RAW with JPEGs

    I usually work on the design end, hence I rarely work (professionally) with files straight-from-camera. I get the stuff after the photographers are done with it. However, that is slightly changing and so I have a question about the Camera Raw plugin

  • How to transfer currency rates to R/3 after dynamic modelling in BPS

    Hi all, I need your advice. I have, for example, a several sales plans, which were composed by using BPS. Each of sales plans depends on currency rates. After comparision these plans, I selected and approved one of them. After plan approval I transfe

  • Kodak photo cd not seen, won't eject

    Hi using a Ti 667 with a combo drive. Installed a Kodak picture cd, it didn't show on desktop and won't eject? Any ideas what I can do other than; the eject button, drive utility eject isn't highlighted, there is no emergency eject? Help! Thanks!

  • Importing FXG Into Flex Application

    I'm currently working on a SWF that is being built using the open source Flex 4.5.x SDK.  Part of the project requires that I import graphics in FXG format.  Since this is my first time handling this kind of import, I decided to build a sample in the