Data Table with Current Week and Those Dates One Year Ago - sql

I'm trying to create one sql table with the current week's data (always changing) as well as those dates data from the previous year. I have multiple tables that I have to join but am not sure how to create it all into one table. Here is what I have so far:
------- CURRENT YEAR -------
DECLARE
#CURRENTDATE DATE,
#BEGINDATE DATE
SET #CURRENTDATE = CONVERT(DATE,GETDATE()) ---// TODAY'S DATE //---
SET #BEGINDATE = DATEADD(DAY, -7, GETDATE()) ---// A WEEK BEFORE TODAY'S DATE //---
SELECT SALES.*, RECRUITS.Recruits
FROM
(
SELECT
CONVERT(VARCHAR(10), A.[ORDER DATE], 101) AS 'DAY'
, 'Sales Revenue Current Year' = FORMAT(SUM(A.[GRAND TOTAL]) ,'C', 'EN-US')
, 'Comm. Sales Volume Current Year' = FORMAT(sum(a. [QUALIFYING VOLUME]), 'C', 'EN-US')
FROM TABLE1 a
WHERE CONVERT(VARCHAR(10), A.[ORDER DATE], 101) >= #BEGINDATE AND CONVERT(VARCHAR(10), A.[ORDER DATE], 101) < #CURRENTDATE
GROUP BY CONVERT(VARCHAR(10), A.[ORDER DATE], 101)
) SALES,
(
SELECT
CONVERT(VARCHAR(10),a.[start date],101) AS 'DAY'
,count(b.[id number]) as Recruits
from TABLE2 a
left join
TABLE3 b
on a.enroller = b. [id number]
WHERE CONVERT(VARCHAR(10), A.[START DATE], 101) >= #BEGINDATE AND CONVERT(VARCHAR(10), A.[START DATE], 101) < #CURRENTDATE
group by a.[start date]
) RECRUITS
WHERE SALES.DAY = RECRUITS.DAY
I have the same script for the previous year. It is the same except I set the dates to -366 and -373 days. Any help would be great!

You can use multiple dates with an "OR", like below, but a better solution would be to use a date dimensional table, a list of every daily date with things like "WeekOfYear", "WeekOfMonth", "QuarterOfYear", "IsHoliday", etc. Then you can join your date against that table and query "where t1.WeekOfYear = t2.WeekOfYear".
DECLARE
#EndDate DATE = GETDATE() ---// TODAY'S DATE //---
, #StartDate DATE = DATEADD(DAY, -7, GETDATE()) ---// A WEEK BEFORE TODAY'S DATE //---
, #LYStartDate DATE = DATEADD(YEAR, -1, GETDATE()) ---// A YEAR BEFORE TODAY'S DATE //---
, #LYEndDate DATE = DATEADD(DAY, -7, DATEADD(YEAR, -1, GETDATE())) ---// A YEAR AND A WEEK BEFORE TODAY'S DATE //---
SELECT SALES.*, RECRUITS.Recruits
FROM
(
SELECT
'DAY' = CONVERT(VARCHAR(10), A.[ORDER DATE], 101)
, 'Sales Revenue Current Year' = FORMAT(SUM(A.[GRAND TOTAL]) ,'C', 'EN-US')
, 'Comm. Sales Volume Current Year' = FORMAT(sum(a. [QUALIFYING VOLUME]), 'C', 'EN-US')
FROM TABLE1 a
WHERE (
(CAST(A.[ORDER DATE] AS DATE) >= #StartDate AND CAST(A.[ORDER DATE] AS DATE) <= #EndDate)
OR
(CAST(A.[ORDER DATE] AS DATE) >= #LYStartDate AND CAST(A.[ORDER DATE] AS DATE) <= #lyEndDate)
)
GROUP BY CAST(A.[ORDER DATE] AS DATE)
) SALES,
(
SELECT
'DAY' = CAST(a.[start date] AS DATE)
, Recruits = COUNT(b.[id number])
FROM TABLE2 a
LEFT JOIN TABLE3 b
ON a.enroller = b. [id number]
WHERE (
(CAST(A.[START DATE] AS DATE) >= #StartDate AND CAST(A.[ORDER DATE] AS DATE) <= #EndDate)
OR
(CAST(A.[START DATE] AS DATE) >= #lyStartDate AND CAST(A.[ORDER DATE] AS DATE) <= #LYEndDate)
GROUP BY CAST(a.[start date] AS DATE)
) RECRUITS
WHERE SALES.DAY = RECRUITS.DAY

Related

SQL- Grouping and counting # of days w/o overlapping days

I am trying to group a total count of days within a month that a patient had a catheter line inserted. The data is broken down into stints so is not contiguous throughout the month. I also do not to count overlapping days between the stints. See screenshot and query below.
DECLARE #start_date DATETIME
DECLARE #end_date DATETIME
SET #start_date = '2/1/2022'
SET #end_date = '2/28/2022';
CREATE TABLE mytable(
Patient_ID INTEGER NOT NULL PRIMARY KEY
,startdate DATE NOT NULL
,enddate DATE NOT NULL
,Type_of_Line VARCHAR(4) NOT NULL
,Insertion_Date DATE NOT NULL
,Removal_Date DATE
,_of_Cath_Days INTEGER NOT NULL
);
INSERT INTO mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-01-16','2022-02-11','Port','2021-08-03 00:00:00.000',NULL,11);
INSERT INTO mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-11','2022-02-15','Port','2021-08-03 00:00:00.000',NULL,5);
INSERT INTO mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-15','2022-02-24','Port','2021-08-03 00:00:00.000',NULL,10);
INSERT INTO mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-24','2022-03-23','Port','2021-08-03 00:00:00.000',NULL,5);
WITH stat
AS (SELECT pt.ptkey,
ptid,
ptptinfusionstatus.startdate,
ptptinfusionstatus.enddate
FROM pt
LEFT JOIN ptptinfusionstatus
ON ptptinfusionstatus.ptkey = pt.ptkey
LEFT JOIN ptinfusionstatus
ON ptinfusionstatus.ptinfusionstatuskey =
ptptinfusionstatus.ptinfusionstatuskey
WHERE ptptinfusionstatus.ptinfusionstatuskey IN ( 1, 5 )),
access1
AS (SELECT d.NAME,
d.pharmacyeventandoutcometypedetailkey,
T.pharmacyeventandoutcometypekey
FROM pharmacyeventandoutcometypedetail d WITH (nolock)
LEFT JOIN pharmacyeventandoutcometype t WITH (nolock)
ON t.pharmacyeventandoutcometypekey =
d.pharmacyeventandoutcometypekey
LEFT JOIN pharmacyeventandoutcomelist l WITH (nolock)
ON l.pharmacyeventandoutcomelistkey =
t.pharmacyeventandoutcomelistkey
WHERE l.pharmacyeventandoutcomelistkey = 2),
access2
AS (SELECT stat.ptkey,
stat.ptid,
stat.startdate,
stat.enddate,
Isnull(devicetype.NAME, '') [Access Device_Type],
ppad.insertiondate [Access Device_Insertion Date],
ppad.removaldate [Access Device_Removal Date]
FROM stat WITH (nolock)
JOIN pharmacyptaccessdevice ppad WITH(nolock)
ON ppad.ptkey = stat.ptkey
LEFT JOIN access1 devicetype WITH (nolock)
ON devicetype.pharmacyeventandoutcometypedetailkey =
ppad.accessdevicetypekey
AND devicetype.pharmacyeventandoutcometypekey = 4)
--***MAIN QUERY***
SELECT access2.[ptid] AS 'Patient ID',
access2.startdate,
access2.enddate,
access2.[access device_type] AS 'Type of Line',
access2.[access device_insertion date] AS 'Insertion Date',
access2.[access device_removal date] AS 'Removal Date',
Datediff(d, CASE WHEN [access device_insertion date] >= #start_date AND
[access device_insertion date] >=access2.startdate THEN
access2.[access device_insertion date] WHEN access2.startdate >=
access2.[access device_insertion date] AND
access2.startdate >= #start_date THEN access2.startdate ELSE #start_date
END,
CASE WHEN #end_date <= Isnull(access2.enddate, #end_date) AND #end_date
<= Isnull(access2.[access device_removal date], #end_date) THEN #end_date
WHEN access2.enddate IS NOT NULL AND access2.enddate < #end_date AND
access2.enddate <= Isnull(access2.[access device_removal date],
access2.enddate) THEN access2.enddate ELSE
access2.[access device_removal date] END) + 1 AS '# of Cath Days'
FROM access2
WHERE access2.startdate <= #end_date
AND ( access2.enddate >= #start_date
OR access2.enddate IS NULL )
AND access2.[access device_insertion date] <= #end_date
AND ( access2.[access device_removal date] >= #start_date
OR access2.[access device_removal date] IS NULL )
AND access2.ptid = '10247'
I tried grouping by patient and adding a sum of days at the patient group level in SQL Reporting Services, but could not get around the overlapping days so the counts are all wrong.
Based on the data provided, below is an example code that will group based on patientId and if start date equals end date then it will subtract 1 from number of days.
DECLARE #start_date DATETIME
DECLARE #end_date DATETIME
SET #start_date = '2/1/2022'
SET #end_date = '2/28/2022';
declare #mytable table(
Patient_ID INTEGER NOT NULL -- PRIMARY KEY
,startdate DATE NOT NULL
,enddate DATE NOT NULL
,Type_of_Line VARCHAR(4) NOT NULL
,Insertion_Date DATE NOT NULL
,Removal_Date DATE
,_of_Cath_Days INTEGER NOT NULL
);
INSERT INTO #mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-01-16','2022-02-11','Port','2021-08-03 00:00:00.000',NULL,11);
INSERT INTO #mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-11','2022-02-15','Port','2021-08-03 00:00:00.000',NULL,5);
INSERT INTO #mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-15','2022-02-24','Port','2021-08-03 00:00:00.000',NULL,10);
INSERT INTO #mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-24','2022-03-23','Port','2021-08-03 00:00:00.000',NULL,5);
select
Patient_ID
, startdate
, enddate
, Type_of_Line
, Insertion_Date
, Removal_Date
, LAG([enddate]) OVER (ORDER BY [startdate]) as compareenddate
from #mytable
select Patient_ID
, min(startdate) as startdate
, max(enddate) as enddate
, max(Type_of_Line) as Type_of_Line
, min(Insertion_Date) as Insertion_Date
, max(Removal_Date) as Removal_Date
, sum(iif(startdate = isnull(compareenddate, '1900-01-01'), _of_Cath_Days - 1, _of_Cath_Days) )
from
(
select
Patient_ID
, startdate
, enddate
, Type_of_Line
, Insertion_Date
, Removal_Date
, _of_Cath_Days
, LAG([enddate]) OVER (ORDER BY [startdate]) as compareenddate
from #mytable
) x
group by Patient_ID
Query result

SQL Date Logic Clause

Having problems understanding how to get the Where clause to work with this date structure.
Here is the principal logic. I want data only from previous March 1 onward and ending on yesterdays date.
Example #1:
So today is Feb 13, 2015 This would mean I need data between (2014-03-01 and 2015-02-12)
Example #2:
Say today is March 20, 2015 This This would mean I need data between (2015-03-01 and 2015-03-19)
The where logic might work but it doesn't like to convert '3/1/' + year. But I'm not sure how else to express it. The first clause is fine its the Case section that is broken.
Query
SELECT [Request Date], [myItem]
FROM myTable
WHERE [Request Date] < CONVERT(VARCHAR(10), GETDATE(), 102)
AND [Request Date] = CASE WHEN
CONVERT(VARCHAR(10), GETDATE(), 102) <
CONVERT(VARCHAR(12), '3/1/' + DATEPART ( year , GETDATE()) , 114)
THEN [Request Date] > CONVERT(VARCHAR(12), '3/1/' + DATEPART ( year , GETDATE()-365) , 114)
ELSE [Request Date] > CONVERT(VARCHAR(12), '3/1/' + DATEPART ( year , GETDATE() , 114)
END
I have also tried
AND [Request Date] = CASE WHEN
CONVERT(VARCHAR(10), GETDATE(), 102) <
'3/1/' + CONVERT(VARCHAR(12), DATEPART ( YYYY , GETDATE()))
THEN [Request Date] > '3/1/' + CONVERT(VARCHAR(12), DATEPART ( YYYY , GETDATE()-364))
ELSE [Request Date] > '3/1/' + CONVERT(VARCHAR(12), DATEPART ( YYYY , GETDATE()))
END
Try this where clause.
WHERE [Request Date]
BETWEEN Cast(CONVERT(VARCHAR(4), Year(Getdate())-1)+ '-03-01' AS DATE)
AND Getdate() - 1
Here Cast(CONVERT(VARCHAR(4), Year(Getdate())-1)+ '-03-01' AS DATE) will fetch the first day of march month. With that add -1 year to get the starting point.
Getdate() - 1 will define the ending point
I'd prefer to create datetime variables for the #from - #to range but if this is for a view I guess you have to do it in the where clause.
SELECT [Request Date], [myItem]
FROM myTable
WHERE [Request Date] < cast(GETDATE() as date)
AND [Request Date] >= CASE WHEN
GETDATE() < CONVERT(datetime, '3/1/' + cast(Year(GETDATE()) as varchar(4)))
THEN CONVERT(datetime, '3/1/' + cast(Year(GETDATE()) - 1 as varchar(4)))
ELSE CONVERT(datetime, '3/1/' + cast(Year(GETDATE()) as varchar(4)))
END
Something like this? Always from Mar 1st onwards, previous year if it's now Mar 1 or earlier, and otherwise this year.
SELECT [Request Date], [myItem]
FROM myTable
WHERE [Request Date] >= dateadd(month, 2, DATEADD(year, DATEDIFF(year, 0, dateadd(month, -2, dateadd(day, -1, getdate()))), 0))
and [Request Date] < DATEADD(day, DATEDIFF(day, 0, getdate()), 0)
First it deducts one day, so that March 1 isn't taking the same year, then it deducts 2 months for getting those dates for previous year, then it rounds it to the year, and then it adds 2 months to get to Mar 1.
In Oracle, I'd compute the lower bound like this:
add_months( trunc( add_months( sysdate, -2 ), 'YEAR'), 2 )
In other words - subtract two months, round down to the start of the year, then add two months.
Hopefully, you can convert this to use appropriate TSQL functions.
Lets work with some test data:
DECLARE #MyDate DATETIME = '3/13/2015'
Going to declare some variable we will set:
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
In this code, I check to see if we are before or after march 1st, and if so we will use either the previous year, or this year for the starting point (fiscal year?)
SELECT #StartDate = CASE WHEN DATEPART(MONTH, #MyDate) < 3 THEN
DATEADD(MONTH, 2, DATEADD(YEAR, DATEDIFF(YEAR, 0, #MyDate) - 1, 0))
ELSE
DATEADD(MONTH, 2, DATEADD(YEAR, DATEDIFF(YEAR, 0, #MyDate), 0))
END,
#EndDate = DATEADD(DAY, DATEDIFF(DAY, 0, #MyDate), 0)
Here is the output:
SELECT #StartDate AS Start, #EndDate AS EndDate
Start EndDate
2015-03-01 00:00:00.000 2015-03-13 00:00:00.000
I would first create a fairly generic user-defined function that does what I need, thus:
create function dbo.start_of_fiscal_year
(
#today date ,
#fiscal_year_start_month int
)
returns date
as
begin
set #today = case coalesce(#today,'')
when '' then current_timestamp
else #today
end
declare #month_start date = dateadd(day,1-datepart(day,#today),#today)
declare #fiscal_month_number int = case sign( datepart(month,#month_start) - #fiscal_year_start_month )
when -1 then 13
else 1
end
+ ( datepart(month,#month_start) - #fiscal_year_start_month )
declare #fiscal_year_start date = dateadd(month,1-#fiscal_month_number,#month_start)
return #fiscal_year_start
end
go
Once you have that you can say things like
declare #today date = current_timetamp
declare #fy_start date = start_of_fiscal_year(#today,3)
select *
from dbo.foo t
where t.report_date >= #fy_start
and t.report_date < #today
or even
select fiscal_year = datepart(year,start_of_fiscal_year(t.report_date,3)) , count(*)
from dbo.foo t
group by datepart(year,start_of_fiscal_year(t.report_date,3))
Your lower bound should be this. You just need to offset the year when month is less than 3 (March).
dateadd(
yy,
year(current_timestamp) - 1900 + case when month(current_timestamp) < 3 then -1 else 0 end,
'19000301'
)
There's no reason to mess around with strings and this consolidates the logic very concisely. I'm also guessing that when current date is March 1 that you want to query the full previous year. So you'll want to adjust the test slightly.
case when (month(dateadd(dd, -1, current_timestamp)) < 3 ...
And just for fun:
dateadd(mm, (12-month(current_timestamp-1))/10*-12+2, cast(year(current_timestamp) as char(4)));

Joining sql queries

Can you help with these two queries?
Query one:
declare #startdate datetime
declare #enddate datetime
set #datainicio='2014-03-01'
set #datafim='2014-03-03'
select right([Location Code],4) as Vehicle,MIN(CAST(CAST([date]AS DATE) AS DATETIME) +
CAST([entry time]AS TIME)) as DaeaMin,min([Veihicle Kms]) as KmsMin,MAX(CAST(CAST([date]AS DATE) AS DATETIME) +
CAST([entry time]AS TIME)) as DateMax,max([Veihicle Kms])as KmsMax
where quantity>=0 and [Location code] like 'v%' and [item no_]='601.0001' and ([date] between #startdate and #enddate)
group by [Location Code]
Query two:
SELECT Vehicles.Designation as Vehicle,
SUM(Locations.DistanceFromLastLocation)/1000 as
KMS,convert(varchar(10),LocationDate,120) as Date
FROM Locations INNER JOIN Vehicles ON Locations.VehicleId = Vehicles.VehicleId
GROUP BY Vehicles.Designation,LocationDate
I want to join these two query by Vehicle and the date in query two must be between the datemin and datemax from the query one.
Help please Thanks.
Hope this helps and is a little easier to understand than the other answers. Note I have included spelling mistakes ;)
declare #startdate datetime
declare #enddate datetime
set #datainicio='2014-03-01'
set #datafim='2014-03-03'
SELECT *
FROM (
select right([Location Code],4) as Vehicle,MIN(CAST(CAST([date]AS DATE) AS DATETIME) +
CAST([entry time]AS TIME)) as DaeaMin,min([Veihicle Kms]) as KmsMin,MAX(CAST(CAST([date]AS DATE) AS DATETIME) +
CAST([entry time]AS TIME)) as DateMax,max([Veihicle Kms])as KmsMax
FROM YOURTABLE
where quantity>=0 and [Location code] like 'v%' and [item no_]='601.0001' and ([date] between #startdate and #enddate)
group by [Location Code]
) x
INNER JOIN (
SELECT Vehicles.Designation as Vehicle,
SUM(Locations.DistanceFromLastLocation)/1000 as
KMS,convert(varchar(10),LocationDate,120) as Date
FROM Locations INNER JOIN Vehicles ON Locations.VehicleId = Vehicles.VehicleId
GROUP BY Vehicles.Designation,LocationDate
) y
ON x.Vehicle = y.Vehicle
AND y.DATE BETWEEN x.DaeaMin AND x.DateMax
Since you have not mentioned from clause in first query, I assume for first query you are fetching data from 'Locations' table.
Below answer may be useful.
;with temp as
(
SELECT Vehicles.Designation as Vehicle,
sum(Locations.DistanceFromLastLocation)/1000 as KMS,
convert(varchar(10),Locations.LocationDate,120) as Date
FROM Locations
INNER JOIN Vehicles
ON Locations.VehicleId = Vehicles.VehicleId
group by Vehicles.Designation,Locations.LocationDate
)
select right(Locations.[Location Code],4) as Vehicle,
MIN(CAST(CAST([Locations.date]AS DATE) AS DATETIME) + CAST([Locations.entry time]AS TIME))
as DateaMin,
min([Locations.Veihicle Kms]) as KmsMin,
MAX(CAST(CAST([Locations.date]AS DATE) AS DATETIME) + CAST([Locations.entry time]AS TIME))
as DateMax,
max([Locations.Veihicle Kms])as KmsMax
FROM Locations
Inner Join temp on
temp.Vehicle = right([Locations.Location Code],4)
where Locations.quantity>=0
and [Locations.Location code] like 'v%'
and [Locations.item no_]='601.0001'
and ([Locations.date] between #startdate and #enddate)
and temp.[Date] between
MIN(CAST(CAST([Locations.date]AS DATE) AS DATETIME) + CAST([Locations.entry time]AS TIME))
and
MAX(CAST(CAST([Locations.date]AS DATE) AS DATETIME) + CAST([Locations.entry time]AS TIME))

Calendar showing null when date begins in previous year

This is the syntax I am using to create my calendar. The issue that I have is that since the startdate of Week1 is in 2012, startdate is showing as null. Is there a way to have the startdate (or enddate in other instances) populate even when it is in a different year? #Winds Of Change ---
That adds in a start date and end date where previously it was null. But what I am after is for example, I need my date range to run Sat - Wed. So let's take week 53 for 2013. The date range should be 12/28/2013 -- 01/01/14. Is there a way to tinker the calander into displaying in that format?
CREATE TABLE dbo.Calendar (
CalendarYear INT NOT NULL,
CalendarWeek INT NOT NULL,
WeekStartDate VARCHAR(50),
WeekEndDate VARCHAR(50),
CONSTRAINT PK_Calendar PRIMARY KEY (
CalendarYear,
CalendarWeek
)
)
SET DATEFIRST 6
DECLARE #StartDate DATETIME,
#NumOfDays INT
SET #StartDate = '20130101'
SET #NumOfDays = 1000;
WITH calendar
AS (
SELECT TOP (#NumOfDays) dateadd(day, row_number() OVER (
ORDER BY sc1.column_id
) - 1, #StartDate) AS CalendarDate
FROM sys.columns sc1
CROSS JOIN sys.columns sc2
)
INSERT INTO dbo.Calendar (
CalendarYear,
CalendarWeek,
WeekStartDate,
WeekEndDate
)
SELECT DATEPART(year, c.CalendarDate) AS Year,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) AS Week, --DATEPART(week, c.CalendarDate) AS Week,
MAX(CASE DATEPART(WEEKDAY, c.CalendarDate)
WHEN 1
THEN convert(VARCHAR(50), c.CalendarDate, 101)
ELSE NULL
END) AS StartDate,
MAX(CASE DATEPART(WEEKDAY, c.CalendarDate)
WHEN 7
THEN convert(VARCHAR(50), c.CalendarDate, 101)
ELSE NULL
END) AS EndDate
FROM calendar c
GROUP BY DATEPART(year, c.CalendarDate),
DATEPART(Week, c.CalendarDate)
ORDER BY Year,
startdate,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) --Week
SELECT *
FROM dbo.Calendar
So your problem is is that you're grouping by week and year, but at the beginning/end of the year, the year begins/ends on a different week. So if the first week starts on Wednesday, it's only a 3 day week for that Year.
I've had a small tinker, and I've got it working so that it displays the first/last day of the year as the start/end date of the week, by changing things around. Here is my modified version:
SELECT
DATEPART(year, c.CalendarDate) AS Year,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) AS Week, --DATEPART(week, c.CalendarDate) AS Week,
convert(VARCHAR(50), MIN(c.CalendarDate), 101) AS StartDate,
convert(VARCHAR(50), MAX(c.CalendarDate), 101) AS EndDate
FROM
calendar c
GROUP BY
DATEPART(year, c.CalendarDate),
DATEPART(Week, c.CalendarDate)
ORDER BY
Year,
startdate,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) --Week
Hope this helps.
EDIT: In response to your comment/edit, have a look at these update statements. Put them after your insert.
EDIT2: Don't use the above insert as well as the updates.
update dbo.Calendar set WeekStartDate = convert(VARCHAR(50), dateadd(day, 1, dateadd(week, -1, cast(WeekEndDate as datetime))), 101)
where WeekStartdate is null
update dbo.Calendar set WeekEndDate = convert(VARCHAR(50), dateadd(day, -1, dateadd(week, 1, WeekStartDate)), 101)
where WeekEndDate is null

Searching Week-wise/Month-wise record counts(number) and the StartDate+EndDate(datetime) of the Week/Month with Search between two Dates

I have a question in connection to this question earlier posted by me:-
Daily/Weekly/Monthly Record Count Search via StoredProcedure
I want to have the Count of Calls on Weekly-basis and Monthly-basis, Daily-basis issue is resolved.
ISSUE NUMBER #1:Weekly-basis Count of Calls and Start-Date and End-Date of Week
I have searched the Start-Date and End-Date of Week including their individual Count of Calls as well in the below-mentioned query. But the problem is that I could not get the result in one single table, although I have used the Temporary Tables(#TempTable+#TempTable2). Kindly help me in this regards.
NOTE:Table Creation commented as for executing more than once.
--CREATE TABLE #TempTable(StartDate datetime,EndDate datetime,CallCount numeric(18,5))
--CREATE TABLE #TempTable2(StartDate datetime,EndDate datetime,CallCount numeric(18,5))
DECLARE #StartDate datetime,#EndDate datetime,#StartDateTemp1 datetime,#StartDateTemp2 datetime,#EndDateTemp datetime,#Period varchar(50);
SET #StartDate='1/1/2010'; SET #EndDate='2/28/2010';
SET #StartDateTemp1=#StartDate; SET #StartDateTemp2=DATEADD(dd, 7, #StartDate );
SET #Period='Weekly';
IF (#Period = 'Weekly')
BEGIN
WHILE ((#StartDate <= #StartDateTemp1) AND (#StartDateTemp2 <= #EndDate))
BEGIN
IF((#StartDateTemp1 < #StartDateTemp2 ) AND (#StartDateTemp1 != #StartDateTemp2) )
BEGIN
SELECT
convert(varchar, #StartDateTemp1, 106) AS 'Start Date',
convert(varchar, #StartDateTemp2, 106) AS 'End Date',
COUNT(*) AS 'Call Count'
FROM TRN_Call
WHERE (CallTime >= #StartDateTemp1 AND CallTime <= #StartDateTemp2 );
END
SET #StartDateTemp1 = DATEADD(dd, 7, #StartDateTemp1);
SET #StartDateTemp2 = DATEADD(dd, 7, #StartDateTemp2);
END
END
ISSUE NUMBER #2:Monthly-basis Count of Calls and Start-Date and End-Date of Week
In this case, I have the same search, but will have to search the Call Counts plus the Start-Date and End-Date of the Month. Kindly help me in this regards as well.
DECLARE #StartDate datetime,#EndDate datetime,#StartDateTemp1 datetime,#StartDateTemp2 datetime,#EndDateTemp datetime,#Period varchar(50);
SET #StartDate='1/1/2010'; SET #EndDate='4/1/2010'; SET #StartDateTemp1=#StartDate;
--SET #StartDateTemp2=#StartDate;
SET #StartDateTemp2=DATEADD(mm, 1, #StartDate );
SET #Period='Monthly';
IF (#Period = 'Monthly')
BEGIN
WHILE ((#StartDate <= #StartDateTemp1) AND (#StartDateTemp2 <= #EndDate))
BEGIN
IF((#StartDateTemp1 < #StartDateTemp2 ) AND (#StartDateTemp1 != #StartDateTemp2) )
BEGIN
SELECT
convert(varchar, #StartDateTemp1, 106) AS 'Start Date',
convert(varchar, #StartDateTemp2, 106) AS 'End Date',
COUNT(*) AS 'Call Count'
FROM TRN_Call
WHERE (CallTime >= #StartDateTemp1 AND CallTime <= #StartDateTemp2 );
END
SET #StartDateTemp1 = DATEADD(mm, 1, #StartDateTemp1);
SET #StartDateTemp2 = DATEADD(mm, 1, #StartDateTemp2);
END
END
I believe following three simple queries suffice for what you need.
Daily
SELECT [Day] = CAST(CAST(CallTime AS INTEGER) AS DATETIME)
, [Call Count] = COUNT(*)
FROM TRN_Call
WHERE CallTime BETWEEN #StartDate AND #EndDate
GROUP BY CAST(CAST(CallTime AS INTEGER) AS DATETIME)
Weekly
SELECT [Week] = DATEPART(ww, CallTime)
, [Year] = DATEPART(yy, CallTime)
, [Call Count] = COUNT(*)
FROM TRN_Call
WHERE CallTime BETWEEN #StartDate AND #EndDate
GROUP BY DATEPART(ww, CallTime), DATEPART(yy, CallTime)
Monthly
SELECT [Month] = DATEPART(mm, CallTime)
, [Year] = DATEPART(yy, CallTime)
, [Call Count] = COUNT(*)
FROM TRN_Call
WHERE CallTime BETWEEN #StartDate AND #EndDate
GROUP BY DATEPART(mm, CallTime), DATEPART(yy, CallTime)
Simple query for find record month wise.....
SELECT invoice_no, created_at,month(created_at) month_no ,count(invoice_no) sale_count FROM sales_invoice WHERE company_id = ' .10 . ' AND status = "Approved" and year(created_at) = year(curdate()) group by month(created_at)enter code here