Consecutive day count with total - sql-server

Is there a way to show if the days go consecutively? I need to show a total for when the date is 5 consecutive.
The data is shown below. Could I put a date range for April like: date between 2019-04-01 and 2019-05-31 and show the DATEPART(WEEK,date) for the first date of the 5 consecutive.
I'd like to show the total of 5 consecutive days like below. It skips the week that did not have a date for 5 consecutively.
Week Total
21 7.50
23 7.50

Something like this should work for you.
SELECT DATEPART(WEEK,[Date]),SUM([Dollar])
FROM [dbo].[TEST]
GROUP BY DATEPART(WEEK,[Date])
HAVING COUNT(DATEPART(WEEK,[Date])) >= 5
Here is a SQL Fiddle.

Related

excel - is it possible to group dates in a column in pivot table?

I have a table where the columns are months. I want the sum of values grouped by 3 months. I was wondering if this is even possible as the group button is grayed out.
January February March ...
999 999 999
999 999 999
999 999 999
the output should look like
January-March ...
8991

Number of weeks and partial weeks between two days calculated wrong

Why is this returning 4 instead of 6?
SET DATEFIRST 1
SELECT DATEDIFF(WEEK, CAST('2017-01-01' AS DATE), CAST('2017-01-31' AS DATE))
Is week as datepart calculating only weeks from monday - sunday (whole weeks)? How to get all weeks - including those which doesn't have seven days ? In the case above answer should be 6.
DATEDIFF counts transitions, not periods (e.g. look at DATEDIFF(year,'20161231','20170101')). It also treats Sunday as the first day of the week. So, how do we compensate for these features? First, we shift our dates so that Mondays are the new Sundays, and second we add 1 to compensate for the Fence-Post error:
declare #Samples table (
StartAt date not null,
EndAt date not null,
SampleName varchar(93) not null
)
insert into #Samples (StartAt,EndAt,SampleName) values
('20170101','20170131','Question - 6'),
('20170102','20170129','Exactly 4'),
('20170102','20170125','3 and a bit, round to 4'),
('20170101','20170129','4 and 1 day, round to 5')
--DATEDIFF counts *transitions*, and always considers Sunday the first day of the week
--We subtract a day from each date so that we're effectively treating Monday as the first day of the week
--We also add one because DATEDIFF counts transitions but we want periods (FencePost/FencePanel)
select *,
DATEDIFF(WEEK, DATEADD(day,-1,StartAt), DATEADD(day,-1,EndAt)) +1
as NumWeeks
from #Samples
Results:
StartAt EndAt SampleName NumWeeks
---------- ---------- -------------------------- -----------
2017-01-01 2017-01-31 Question - 6 6
2017-01-02 2017-01-29 Exactly 4 4
2017-01-02 2017-01-25 3 and a bit, round to 4 4
2017-01-01 2017-01-29 4 and 1 day, round to 5 5
If this doesn't match what you want, perhaps you can adopt and adapt my #Samples table to show the results you do expect.
What you ask though, is how many weeks are covered by a range, not how many weeks are between two dates.
DATEDIFF always uses Sunday when calculating week transitions.
This isn't a bug, it's done to ensure the function is deterministic and returns the same value, for every query, no matter the DATEFIRST setting. From the documentation
Specifying SET DATEFIRST has no effect on DATEDIFF. DATEDIFF always uses Sunday as the first day of the week to ensure the function is deterministic.
One solution would be to calculate the difference between the week numbers of the start and end dates, when the first day is Monday. 1 is added to the difference to take account of the first week as well:
SET DATEFIRST 1;
select 1 +datepart(WEEK,'20170131') - datepart(WEEK,'20170101')
That's a fragile calculation though that breaks if DATEFIRST changes or if one of the dates is on a different year.
You could use ISO Weeks to get rid of SET DATEFIRST:
select 1 +datepart(ISO_WEEK,'20170131') - datepart(ISO_WEEK,'20170101')
but that would fail for 2017-01-01 because Sunday is counted as Week 52 of the previous year.
A far better solution though would be to count the distinct week numbers using a Calendar table that contains dates and different week numbers to cover multiple business requirements, eg both normal and ISO Week numbers, or business calendars based on a 4-4-5 calendar.
In this case, you could just count distinct week numbers:
SELECT COUNT(DISTINCT Calendar.IsoWeek )
from Calendar
where date between '20170101' and '20170131'
If the table doesn't have an ISO Week column, you can use DATEPART:
select count (distinct datepart(ISO_WEEK,date) )
from Calendar
where date between '20170101' and '20170131'

Pivot or unpivot a table

I have a table in SQL that I need to pivot or unpivot (not sure which). The table consists of days (as represented by workdays##1, workdays##2, workdays##3,etc.) The values under these days are a business day value for the month. Other columns in this table are Company, Year, Monthnum which should remain as columns. So it looks something like this:
SQL table
Company Year Monthnum workday##1 workday##2 workday##3 workday##4
US 2016 8 1 2 3 4
I need the workday##'s (renamed as day of month and substringed to just the number portion) to pivot to rows and the values under them to be put in one column with the header businessday. Future
Company Year Monthnum Dayofmonth Businessday
US 2016 8 1 (workday##1) 1
US 2016 8 2 (workday##2) 2
US 2016 8 3 (workday##3) 3
US 2016 8 4 (workday##4) 4
This table represents the year and month and the number of business days per month. From this I will be doing some month to date calculations against sales goals on a daily basis.

SQL Query-Multiple date ranges

I want to fetch some data from DB by giving multiple date ranges. Example,in February I want to get weekly report from a table in this order Feb 01 to 07, Feb 07 to 14, Feb 14 to 21, Feb 21 to 28 and Feb 28 to Mar 01. In DB the records are stored in a daily wise not in weekly wise. I want to cluster it as weekly wise and calculate sum then show the result. Please help me if you know this case.
For clear cut view, consider 3 tables & its columns.
Table A:id,timestamp (comment-data is inserted daily)
Table B:id,fruits
Table C:id,fruits_type
Result:
fruits_type count(id) timestamp
apple 3 01-02-2016 to 07-02-2016
orange 5 01-02-2016 to 07-02-2016
pineapple 8 01-02-2016 to 07-02-2016
apple 4 07-02-2016 to 14-02-2016
orange 5 07-02-2016 to 14-02-2016
Conditions:id should match among 3 tables;fetch data by providing group by fruits_type and timestamp should be in weekly wise.
Please help if you know this
To get the sum of all values between two dates you would do it like this:
SELECT SUM(Column1)
FROM Table1
WHERE Date1 BETWEEN '2/1/2016' AND Date1 <'2/7/2016'
If you want to make it more flexible and have the query get the last week's sum you can use the DATEADD function to lag by one week:
SELECT SUM(Column1)
FROM Table1
WHERE Date1 BETWEEN DATEADD(week, -1, GETDATE()) AND Date1 < GETDATE()
If you want the result set to include a row for each week, you can use UNION to merge the queries.

SQL Query for SSRS report

I would like to create an ssrs report as below --
I have the following columns to be displayed-
| Tickets | Tickets |
| scanned on| scanned on|
Attraction | Hour | 09/08/2014| 09/09/2014| 09/10/2014| Day 4| Day 5| Day 6| 09/14/2014
Monday Tuesday Wednesday ...................... Sunday
U Mueseum | 9:00 AM | 10 | 40 |
10:00 aM |
..
..
..
..
..
23:00 AM
I will get the Start Date and End Date from the user. Now my problem is that I want a query for 7 days starting from the Start Date selected by the user to the End Date and for each hour i.e. for 1 day it would be 24 hrs, so 24*7 hours in total. When I display the value for scans in my current sql query it displays just for one day. How can I do it for 7 days, and the value of scans for that date should be displayed in the respective week day ie. Monday or Tuesday and so on. I am not able to get as to for each date and each hour the scan value changes, so I am confused and mixing up all here. The values for each hour on each day should be different and there is only one scan column, so how will the distinct values show up in the table.
I used the pivot table to convert the name of the week day from rows to individual columns.
Then the problem arises for ssrs report. How can this be executed in an ssrs report where the rows are for each hour and the columns displays the dates of the week selected. How can I achieve that in ssrs? I am getting currently for only 24 hrs, but i want the report to run for all 24 hrs for 7 days and should display the value side by side for each hour in each week day column.
Thank you.
Pass in one parameter into your stored procedure called #StartDate.
In SQL create the #EndDate like this
DECLARE #EndDate DATETIME
SET #EndDate = DATEADD("d",7,#StartDate)
Return your date information in an hour and a day column. Then use the grouping feature in ssrs to display the data.
I hope this helps you get a bit further with your issue.
Bobby
You could do this pretty easily with a Date Dimension table and a PIVOT operator. Give that a try.

Resources