SQL Query Syntax Error near FROM - tsql

Getting a syntac error on lines 65 and 95:
Use PARCS_DB
GO
TRUNCATE TABLE tbl_Utilities_PARCS_LiveValue
TRUNCATE TABLE tbl_Utilities_PARCS_Totals
TRUNCATE TABLE tbl_Utilities_PARCS_YTD
TRUNCATE TABLE tbl_Utilities_CUB_LiveValue
TRUNCATE TABLE tbl_Utilities_CUB_Totals
TRUNCATE TABLE tbl_Utilities_CUB_YTD
TRUNCATE TABLE tbl_Utilities_BLDG1_LiveValue
TRUNCATE TABLE tbl_Utilities_BLDG1_Totals
TRUNCATE TABLE tbl_Utilities_BLDG1_YTD
GO
DECLARE #Year INT;
SET #Year = 2014;
-- CONVERT TO A DATE TO ALLOW A SARGEABLE PREDICATE IN THE WHERE CLAUSE
DECLARE #Date SMALLDATETIME;
SET #Date = CONVERT(SMALLDATETIME, CONVERT(CHAR(4), #Year), 112);
-- GET PF OLDTOTAL VALUES FROM HISTORY.
INSERT INTO PARCS_DB.dbo.tbl_Utilities_PARCS_Totals
(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
SELECT
Jan = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 2 THEN value END),
Feb = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 3 THEN value END),
Mar = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 4 THEN value END),
Apr = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 5 THEN value END),
May = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 6 THEN value END),
Jun = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 7 THEN value END),
Jul = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 8 THEN value END),
Aug = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 9 THEN value END),
Sep = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 10 THEN value END),
Oct = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 11 THEN value END),
Nov = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 12 THEN value END),
Dec = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 1 AND DATEPART(YEAR,DateTime) = DATEADD(YEAR, 1, #Date) THEN value END)
FROM runtime.dbo.History
WHERE Tagname IN ('FQI_PA_B_001.OldTotal','FQI_PS_B_001.OldTotal','FQI_CW_B_002.OldTotal','FQI_NCW_B_001.OldTotal','FQI_NCW_B_002.OldTotal')
AND wwVersion = 'Latest'
AND DateTime >= #Date
AND DateTime < DATEADD(YEAR, 1, #Date)
GROUP BY TagName;
-- GET PF LIVE VALUES.
INSERT INTO PARCS_DB.dbo.tbl_Utilities_PARCS_LiveValue
(Value)
SELECT Value
FROM runtime.dbo.v_live
WHERE Tagname IN ('FQI_CW_B_002.Total','FQI_NCW_B_001.Total','FQI_NCW_B_002.Total','FQI_PA_B_001.Total','FQI_PS_B_001.Total')
-- GET CUB OLDTOTAL VALUES FROM HISTORY.
INSERT INTO PARCS_DB.dbo.tbl_Utilities_CUB_Totals
(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
SELECT
Jan = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 2 THEN value END),
Feb = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 3 THEN value END),
Mar = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 4 THEN value END),
Apr = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 5 THEN value END),
May = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 6 THEN value END),
Jun = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 7 THEN value END),
Jul = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 8 THEN value END),
Aug = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 9 THEN value END),
Sep = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 10 THEN value END),
Oct = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 11 THEN value END),
Nov = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 12 THEN value END),
Dec = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 1 AND DATEPART(YEAR,DateTime) = DATEADD(YEAR, 1, #Date) THEN value END)
FROM RTPCUBHIST_001.runtime.dbo.History
WHERE Tagname IN ('FQI_DW_A_01.OldTotal','BOA001_STM_TOTAL.OldTotal','BOA002_STM_TOTAL.OldTotal')
AND wwVersion = 'Latest'
AND DateTime >= #Date
AND DateTime < DATEADD(YEAR, 1, #Date)
GROUP BY TagName;
-- GET CUB LIVE VALUES.
INSERT INTO PARCS_DB.dbo.tbl_Utilities_CUB_LiveValue
(Value)
SELECT
FROM RTPCUBHIST_001.runtime.dbo.v_live
WHERE Tagname IN ('BOA001_STM_TOTAL.Total','BOA002_STM_TOTAL.Total','FQI_DW_A_01.Total')
-- GET BLDG1 OLDTOTAL VALUES FROM HISTORY.
INSERT INTO PARCS_DB.dbo.tbl_Utilities_BLDG1_Totals
(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
SELECT
Jan = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 2 THEN value END),
Feb = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 3 THEN value END),
Mar = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 4 THEN value END),
Apr = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 5 THEN value END),
May = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 6 THEN value END),
Jun = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 7 THEN value END),
Jul = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 8 THEN value END),
Aug = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 9 THEN value END),
Sep = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 10 THEN value END),
Oct = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 11 THEN value END),
Nov = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 12 THEN value END),
Dec = MAX(CASE WHEN DATEPART(MONTH, DateTime) = 1 AND DATEPART(YEAR,DateTime) = DATEADD(YEAR, 1, #Date) THEN value END)
FROM RTPBASHIST01.runtime.dbo.History
WHERE Tagname IN ('PROC_AIR_TOTAL.OldTotal','PLNT_STM_TOTAL.OldTotal','DOM_WTR_TOTAL.OldTotal','SAN_SEW_TOTAL.OldTotal')
AND wwVersion = 'Latest'
AND DateTime >= #Date
AND DateTime < DATEADD(YEAR, 1, #Date)
GROUP BY TagName;
-- GET BLDG1 LIVE VALUES
INSERT INTO PARCS_DB.dbo.tbl_Utilities_BLDG1_LiveValue
(Value)
SELECT
FROM RTPBASHIST01.runtime.dbo.v_live
WHERE Tagname IN ('DOM_WTR_TOTAL.Total','PLNT_STM_TOTAL.Total','PROC_AIR_TOTAL.Total','SAN_SEW_TOTAL.Total')
the first instance using the FROM statement works fine, but the replicated statements after that throw the error. Only difference is that for the two erroring out I'm referencing a linked server. Any ideas?

-- GET CUB LIVE VALUES.
INSERT INTO PARCS_DB.dbo.tbl_Utilities_CUB_LiveValue
(Value)
SELECT --NEED TO PUT A COLUMN NAME HERE
FROM RTPCUBHIST_001.runtime.dbo.v_live
WHERE Tagname IN ('BOA001_STM_TOTAL.Total','BOA002_STM_TOTAL.Total','FQI_DW_A_01.Total')
You don't have a column listed in the select clause.
You also have the same problem at the end of your code block near the comment -- GET BLDG1 LIVE VALUES

Related

How can I get T-SQL to include correct data from last month

In the below query I return data for past 5 months, unfortunately I can not get it to include correct count from current month (June 2021), it ruturns 0 where as it should have returned 2 since I have 2 entries with StartDate 14-06-2021 and 17-06-2021 which should have been in this count.. How can I fix this?.
The output I get (missing 2 in month 6)
year month EmployeeStartet
2021 2 8
2021 3 0
2021 4 0
2021 5 4
2021 6 0
My Query
declare #thismonth1 as Date = DateAdd(
d,
1 - DatePart(d, CURRENT_TIMESTAMP),
CURRENT_TIMESTAMP
);
declare #lastMonth1 as Date = DateAdd(
d,
1 - DatePart(d, CURRENT_TIMESTAMP),
CURRENT_TIMESTAMP
);
declare #firstMonth1 as Date = DateAdd(m, -4, #lastMonth1);
WITH months AS (
SELECT
#firstMonth1 AS thisMonth
UNION ALL
SELECT
DateAdd(m, 1, thisMonth) AS thisMonth
FROM
months
WHERE
thisMonth < #lastMonth1
),
data AS (
SELECT
YEAR(StartDate) year,
MONTH(StartDate) month,
COUNT(StartDate) EmployeeStartet
FROM
EFP_EmploymentUser
WHERE
EmployType = 'fixed'
AND StartDate BETWEEN #firstmonth1
AND #thismonth1
GROUP BY
YEAR(StartDate),
MONTH(StartDate)
)
SELECT
YEAR(m.thisMonth) AS year,
MONTH(m.thisMonth) AS month,
ISNULL(d.EmployeeStartet, 0) AS EmployeeStartet
FROM
months m
LEFT OUTER JOIN data d ON d.year = YEAR(m.thisMonth)
AND d.month = MONTH(m.thisMonth)
ORDER BY
m.thisMonth ASC;
Try
declare #thismonth1 as Date = DateAdd(d, 1 - DatePart(d, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP);
declare #lastMonth1 as Date = DateAdd(d, 1 - DatePart(d, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP);
declare #firstMonth1 as Date = DateAdd(m, -4, #lastMonth1);
select #thismonth1, #lastMonth1, #firstMonth1;
This gives you
#thismonth1
#lastMonth1
#firstMonth1
2021-06-01
2021-06-01
2021-02-01
Correct #lastMonth1 and your query will run just fine. You can use EOMONTH for this.

Multiple cases that allows different conversion of column that is being checked in WHERE CASE WHEN clause

SELECT Clmn
FROM Tbl T
INNER JOIN SomeotherTbl
WHERE CONVERT(varchar(10), T.[Date], 120) =
CASE #SortOrder
WHEN '1' THEN CONVERT(varchar(10), GETDATE(), 120)
WHEN '2' THEN CONVERT(varchar(7), GETDATE(), 120)
WHEN '3' THEN CONVERT(varchar(4), GETDATE(), 120)
END
So i have a Date column that i converted to varchar , but i would like to convert it to different length according to #SortOrder , what's the best solution ?
Use Like instead of =:
WHERE CONVERT(varchar(10),D.[Date],120) LIKE
CASE #SortOrder
WHEN '1' THEN CONVERT(varchar(10),GETDATE(),120)
WHEN '2' THEN CONVERT(varchar(7),GETDATE(),120) +'%'
WHEN '3' THEN CONVERT(varchar(4),GETDATE(),120) +'%'
END
Another option (without using case) is this:
WHERE (#SortOrder > '3' OR YEAR(D.[Date]) = YEAR(GETDATE()))
AND (#SortOrder > '2' OR MONTH(D.[Date]) = MONTH(GETDATE()))
AND (#SortOrder > '1' OR DAY(D.[Date]) = DAY(GETDATE()))
And yet another option, that will work for versions 2012 or higher, and is a little more complicated, but if you have an index on the [Date] column will allow SQL Server to use it:
DECLARE #Date date = GETDATE()
DECLARE #ThisMonth date = DATEFROMPARTS(YEAR(#Date), MONTH(#Date), 1)
DECLARE #ThisYear date = DATEFROMPARTS(YEAR(#Date), 1, 1)
SELECT ...
FROM ...
WHERE
(#SortOrder = '1' AND D.[Date] = #Date)
OR (#SortOrder = '2' AND D.[Date] >= #ThisMonth AND D.[Date] < DATEADD(MONTH, 1, #ThisMonth))
OR (#SortOrder = '3' AND D.[Date] >= #ThisYear AND D.[Date] < DATEADD(YEAR, 1, #ThisYear))
You can see a live demo on rextester.
If you want to compare year, month, and day there are better ways
select CONVERT(varchar(10), GETDATE(), 120), CONVERT(varchar(7), GETDATE(), 120), CONVERT(varchar(4), GETDATE(), 120)
, DATEPART(year, getdate()), DATEPART(month, getdate()), DATEPART(day, getdate())
2018-02-22 2018-02 2018 2018 2 22

Why is there a difference in my SQL output

This is puzzling me no end, and I know it might be tough without the data but thought it might be a longshot to post here.
Here goes, the first code I received was this
USE [Radiotherapy]
GO
if exists (
select * from tempdb.dbo.sysobjects o
where o.xtype in ('U')
and o.id = object_id(N'tempdb..#MySampleTemp')
)
DROP TABLE #MySampleTemp;
if exists (
select * from tempdb.dbo.sysobjects o
where o.xtype in ('U')
and o.id = object_id(N'tempdb..#MyPivotTemp')
)
DROP TABLE #MyPivotTemp;
SELECT [AttendanceNumber]
,CASE WHEN AgeAtExamDate BETWEEN 0 AND 5 THEN '0-5'
WHEN AgeAtExamDate BETWEEN 6 AND 18 THEN '6-18'
WHEN AgeAtExamDate BETWEEN 19 AND 150 THEN '19+'
ELSE 'Error' END AS AgeRange
,[LocalPatientIdentifier]
,[ExaminationDate]
,[ExamExaminationCode] INTO #MySampleTemp
FROM [dbo].[tblRadiologyData]
WHERE AttendanceSiteCode IN('CNM','RNM')
--AND AttendanceStatus NOT IN ( 'Appt', 'Booked In', 'Cancelled', 'Pending' )
--AND AttendancePatientGroup = 'Out Patient'
--AND AttendancePatientCategory IN ( 'EU', 'Military', 'N.H.S.' )
--AND AttendanceSourceName <> 'PACs Support'
AND [ExaminationDate] >= '1 OCTOBER 2015' --
ORDER BY [AttendanceNumber], CASE WHEN AgeAtExamDate BETWEEN 0 AND 5 THEN '0-5'
WHEN AgeAtExamDate BETWEEN 6 AND 18 THEN '6-18'
WHEN AgeAtExamDate BETWEEN 19 AND 150 THEN '19+'
ELSE 'Error' END, [LocalPatientIdentifier], [ExaminationDate], ExamExaminationCode
SELECT [AttendanceNumber],AgeRange,[LocalPatientIdentifier],[ExaminationDate], 1 AS ExamCount,
[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14] INTO #MyPivotTemp
FROM
(
SELECT *,
row_number() OVER(PARTITION BY [AttendanceNumber]
ORDER BY [AttendanceNumber], [LocalPatientIdentifier]) rn
FROM #MySampleTemp
) AS st
pivot
(
MAX(ExamExaminationCode)
FOR rn in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14])
) AS pivottable
SELECT
[1] AS Exam01,
[2] AS Exam02,
[3] AS Exam03,
[4] AS Exam04,
[5] AS Exam05,
[6] AS Exam06,
[7] AS Exam07,
[8] AS Exam08,
[9] AS Exam09,
[10] AS Exam10,
[11] AS Exam11,
[12] AS Exam12,
[13] AS Exam13,
[14] AS Exam14,
COUNT(ExamCount) AS [No. Attendances]
FROM #MyPivotTemp
GROUP BY [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14]
ORDER BY [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14]
What I tried to do was replicate this in query as follows:
USE [Radiotherapy]
;With CTE AS (SELECT s.attendanceNumber,
MAX(CASE WHEN s.rnk = 1 THEN s.ExamExaminationCode END) as examCode1,
MAX(CASE WHEN s.rnk = 2 THEN s.ExamExaminationCode END) as examCode2,
MAX(CASE WHEN s.rnk = 3 THEN s.ExamExaminationCode END) as examCode3,
MAX(CASE WHEN s.rnk = 4 THEN s.ExamExaminationCode END) as examCode4,
MAX(CASE WHEN s.rnk = 5 THEN s.ExamExaminationCode END) as examCode5,
MAX(CASE WHEN s.rnk = 6 THEN s.ExamExaminationCode END) as examCode6,
MAX(CASE WHEN s.rnk = 7 THEN s.ExamExaminationCode END) as examCode7,
MAX(CASE WHEN s.rnk = 8 THEN s.ExamExaminationCode END) as examCode8,
MAX(CASE WHEN s.rnk = 9 THEN s.ExamExaminationCode END) as examCode9,
MAX(CASE WHEN s.rnk = 10 THEN s.ExamExaminationCode END) as examCode10,
MAX(CASE WHEN s.rnk = 11 THEN s.ExamExaminationCode END) as examCode11,
MAX(CASE WHEN s.rnk = 12 THEN s.ExamExaminationCode END) as examCode12,
MAX(CASE WHEN s.rnk = 13 THEN s.ExamExaminationCode END) as examCode13,
MAX(CASE WHEN s.rnk = 14 THEN s.ExamExaminationCode END) as examCode14
FROM (
SELECT [AttendanceNumber]
,[ExaminationDate]
,[ExamExaminationCode]
,ROW_NUMBER() OVER(PARTITION BY [AttendanceNumber]
ORDER BY [RadiologyID]) as rnk --Ordered by date ASC
FROM [Radiotherapy].[dbo].[tblRadiologyData] rd
where rd.ExaminationDate >= '01 october 2015'
and rd.AttendanceSiteCode IN('CNM','RNM') ) s
GROUP BY s.attendanceNumber)
Select CTE.examCode1,
CTE.examCode2,
CTE.examCode3,
CTE.examCode4,
CTE.examCode5,
CTE.examCode6,
CTE.examCode7,
CTE.examCode8,
CTE.examCode9,
CTE.examCode10,
CTE.examCode11,
CTE.examCode12,
CTE.examCode13,
CTE.examCode14,
COUNT(CTE.AttendanceNumber) as [No of occurances]
from CTE
GROUP by CTE.examCode1,
CTE.examCode2,
CTE.examCode3,
CTE.examCode4,
CTE.examCode5,
CTE.examCode6,
CTE.examCode7,
CTE.examCode8,
CTE.examCode9,
CTE.examCode10,
CTE.examCode11,
CTE.examCode12,
CTE.examCode13,
CTE.examCode14
ORDER BY CTE.examCode1
Great I thought until my code returned more results which puzzled me. Having broken it down I found the offending code from the original query:
ORDER BY [AttendanceNumber], CASE WHEN AgeAtExamDate BETWEEN 0 AND 5 THEN '0-5'
WHEN AgeAtExamDate BETWEEN 6 AND 18 THEN '6-18'
WHEN AgeAtExamDate BETWEEN 19 AND 150 THEN '19+'
ELSE 'Error' END, [LocalPatientIdentifier], [ExaminationDate], ExamExaminationCode
When I removed this from the first query the results matched, but my question is how and why is an ORDER BY affecting the output. I assumed this was just showing how the results are ordered? Understanding why code is doing what it's doing is something I really need to get my head around. Any advise more than welcome.
Probably it have something to do with this piece of code:
SELECT *,
row_number() OVER(PARTITION BY [AttendanceNumber]
ORDER BY [AttendanceNumber], [LocalPatientIdentifier]) rn
FROM #MySampleTemp
Obviously your ordering is not breaking a tie(it isn't deterministic) and it produces rank number differently when you have ordered data in temp table and when not ordered. Try to add some PK to your temp table so the above code will look like:
SELECT *,
row_number() OVER(PARTITION BY [AttendanceNumber]
ORDER BY [AttendanceNumber], [LocalPatientIdentifier], [SomePK]) rn
FROM #MySampleTemp
Then removing ordering from first select statement will not have an effect on the result set.

Count orders by days of the week, adding Saturday & Sunday counts to Friday

I would like to get the count of ordered items from monday to sunday but adding saturday and sunday orders to fridays, so the query results would only display Orderdates (Monday to Friday)
I have this sql already that shows orders for every single day of the week:
select DATENAME(weekday,orderdate) Day,CONVERT(VARCHAR(10), orderdate, 103) orderdate,
COUNT(orderdate) Orders
from Orders_tb
where orderDate >= '2012-03-01 00:00:00.000'
and orderDate <= '2012-03-31 00:00:00.000'
group by datepart(day,orderDate),orderdate,DATENAME(weekday,orderdate)
Thanks for your input!
EDIT after clarification.
Use case to change weekend days to friday. Derived table is employed to avoid the need to replicate the same expression everywhere orderdate is needed.
select DATENAME(weekday,orderdate_trimmed) Day,
CONVERT(VARCHAR(10), orderdate_trimmed, 103) orderdate,
COUNT(orderdate_trimmed) Orders
from
(
select *,
order_date -
case DATENAME(weekday,orderdate)
when 'Saturday' then 1
when 'Sunday' then 2
else 0
end
orderdate_trimmed
from Orders_tb
) a
where orderDate >= '2012-03-01 00:00:00.000'
and orderDate <= '2012-03-31 00:00:00.000'
group by orderdate_trimmed
You might count matching days only by use of case statement:
select COUNT(orderdate) TotalOrders,
COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Monday' then 1 end) Monday,
COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Tuesday' then 1 end) Tuesday,
COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Wednesday' then 1 end) Wednesday,
COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Thursday' then 1 end) Thursday,
COUNT(CASE WHEN DATENAME(weekday,orderdate) = 'Friday'
OR DATENAME(weekday,orderdate) = 'Saturday'
OR DATENAME(weekday,orderdate) = 'Sunday'
THEN 1 end) Friday
from Orders_tb
where orderDate >= '2012-03-01 00:00:00.000'
and orderDate <= '2012-03-31 00:00:00.000'
A warning about dates: as a date can contain time portion it would be wiser to compare like this:
where orderDate >= '2012-03-01 00:00:00.000'
and orderDate < '2012-04-01 00:00:00.000'

Understanding TSQL Coalesce function

I am trying to select all 12 months / year. And I thought following TSQL code would do this. However, this does not include all months like I want. What is the cause of this? This is modified code:
DECLARE #END_YEAR VARCHAR(10)
DECLARE #END_MONTH VARCHAR(10)
SET #END_YEAR = '2010'
SET #END_MONTH = '10'
DECLARE #TheMonthLastDate DATETIME
DECLARE #TempDate DATETIME
SET #TempDate = '2010-11-01 00:00:00.000'
SET #TheMonthLastDate = '2010-11-01 00:00:00.000'
;with months
as
(
select dateadd(month, -1, dateadd(day, datediff(day, 0, #TempDate), 0)) as m
union all
select dateadd(month, -1, m)
from months
where m > dateadd(month, -12, #TempDate)
)
,yourTable(DateOpened, DateClosed)
as
(select TSK_START_DATE, BTK_CLOSED_DATE
FROM [PROC].ALL_AUDIT
WHERE
(BTK_CLOSED_DATE < #TheMonthLastDate OR
TSK_START_DATE < #TheMonthLastDate
)
)
select yt.DateClosed 'r2', m.m 'r3',
month(coalesce(yt.DateClosed, m.m)) as 'MonthClosed',
year(coalesce(yt.DateClosed, m.m)) as 'YearClosed'
from months m
left join yourTable yt
on
( datepart(year, yt.DateClosed) = DATEPART(year, m.m)
and datepart(month, yt.DateClosed) = DATEPART(month, m.m)
or
datepart(year, yt.DateOpened) = DATEPART(year, m.m)
and datepart(month, yt.DateOpened) = DATEPART(month, m.m)
)
AND year(coalesce(yt.DateClosed, m.m)) = 2010
order by yt.DateClosed
So above query does not return all months. But if I change above WHERE lines to:
FROM [PROC].ALL_AUDIT
WHERE
BTK_CLOSED_DATE < #TheMonthLastDate
then this query does return all 12 months. How can this be?
Output that I want and that I see when WHERE is BTK_CLOSED_DATE < #TheMonthLastDate:
r2 r3 MonthClosed YearClosed
NULL 2010-06-01 00:00:00.000 6 2010
NULL 2009-11-01 00:00:00.000 11 2009
2010-01-06 20:02:19.127 2010-01-01 00:00:00.000 1 2010
2010-01-27 23:13:45.570 2010-01-01 00:00:00.000 1 2010
2010-02-15 14:49:14.427 2010-02-01 00:00:00.000 2 2010
2010-02-15 14:49:14.427 2009-12-01 00:00:00.000 2 2010
But if I instead use WHERE:
(BTK_CLOSED_DATE < #TheMonthLastDate OR
TSK_START_DATE < #TheMonthLastDate
)
then I see:
r2 r3 MonthClosed YearClosed
NULL 2010-10-01 00:00:00.000 10 2010
NULL 2010-09-01 00:00:00.000 9 2010
NULL 2010-09-01 00:00:00.000 9 2010
NULL 2010-08-01 00:00:00.000 8 2010
NULL 2010-08-01 00:00:00.000 8 2010
...
So notice that in first result I see NULL for June 2010, which is what I want.
I think the problem has something to do with the fact that my data contains 2009-2011 data, but I only compare months and not years. How would I add in this additional logic?
The only place where you are reducing the data is with the WHERE clause you have already identified. Therefore, the reason you are not getting all the months you expect is down to the column TSK_START_DATE not being less than #TheMonthLastDate for all months.
To prove this hypothesis, run the following section of your query (I have commented out part of the where clause and removed everything under 'yourTable' cte). The results should show you what is being returned in the TSK_Start_Date column for your missing months and help you identify why the rows are missing when applying the < #TheMonthLastDate clause.
DECLARE #END_YEAR VARCHAR(10)
DECLARE #END_MONTH VARCHAR(10)
SET #END_YEAR = '2010'
SET #END_MONTH = '10'
DECLARE #TheMonthLastDate DATETIME
DECLARE #TempDate DATETIME
SET #TempDate = '2010-11-01 00:00:00.000'
SET #TheMonthLastDate = '2010-11-01 00:00:00.000'
;with months
as
(
select dateadd(month, -1, dateadd(day, datediff(day, 0, #TempDate), 0)) as m
union all
select dateadd(month, -1, m)
from months
where m > dateadd(month, -12, #TempDate)
)
,yourTable(DateOpened, DateClosed)
as
(select TSK_START_DATE, BTK_CLOSED_DATE
FROM [PROC].ALL_AUDIT
WHERE
(BTK_CLOSED_DATE < #TheMonthLastDate OR
--TSK_START_DATE < #TheMonthLastDate
)
)
select * , #TheMonthLastDate TheMonthLastDate from yourTable