I have a table chequeBounce with columns
Accountid ,Accountname,Chdate,chno,chamount
Now, I am creating a query which results the count of Accountid in a month. I need to increment the count of current Accountid month with previous month value based on date select by user.
Anybody can guide?
It's hard to know exactly what it is that you want from your question, but I made a few assumptions myself and came up with a stored procedure that might do what you want. The reason I choose a stored procedure is beacuse you imply that there should be a user defined variable.
So first of all, create this Stored Procedure:
CREATE PROCEDURE dbo.Get_Count
#month1 int,
#month2 int
AS
SELECT [source].AccountName, sum([source].chamount) as [sum of amount], count([source].AccountID) as [no of AccountID in specified months] FROM
(SELECT
AccountID, AccountName, chno, chamount
FROM chequeBounce
WHERE
MONTH(Chdate) = #month1
UNION ALL
SELECT
AccountID, AccountName, chno, chamount
FROM chequeBounce
WHERE
MONTH(Chdate) = #month2) as [source]
GROUP BY [source].AccountID, [source].AccountName, [source].chamount
RETURN 0
This Stored Procedure takes two parameters, #month1, and #month2. Then it runs two queries. One with a where statement that matches #month1 and another that does the exact same, but on #month2. It then unions them both together into one query and counts how many entries there is on each AccountID for the specified months. It allso sums the amount up the same way. You run the procedure by typing exec Get_Count followed by the two months you want to count on. Like this, if you want February and March:
exec Get_Count 2, 3
The results from above query could look something like this:
AccountName sum of amount no of AccountID in specified months
-------------------------------------------------- --------------------- ---------------
NameOne 200.00 2
NameTwo 100.00 1
NameThree 100.00 1
NameFour 200.00 2
NameFive 100.00 1
In this example no of AccountID in specified months is the count of how many occurences there is on each accountID for the specified months (2, 3).
This is the data I've used:
create table chequeBounce (
AccountID int,
AccountName varchar(50),
Chdate date,
chno int,
chamount money,
)
insert into chequeBounce VALUES
(1, 'NameOne', GETDATE(), 123, 100)
,(2, 'NameTwo', GETDATE(), 123, 100)
,(3, 'NameThree', GETDATE(), 123, 100)
,(4, 'NameFour', GETDATE(), 123, 100)
,(5, 'NameFive', GETDATE(), 123, 100)
,(1, 'NameOne', DATEADD(mm, -1, GETDATE()), 123, 100)
,(2, 'NameTwo', DATEADD(mm, -2, GETDATE()), 123, 100)
,(4, 'NameFour', DATEADD(mm, -4, GETDATE()), 123, 100)
,(5, 'NameFive', DATEADD(mm, -5, GETDATE()), 123, 100)
,(1, 'NameOne', DATEADD(mm, -2, GETDATE()), 123, 100)
,(2, 'NameTwo', DATEADD(mm, -3, GETDATE()), 123, 100)
,(4, 'NameFour', DATEADD(mm, -5, GETDATE()), 123, 100)
,(4, 'NameFour', DATEADD(mm, -3, GETDATE()), 123, 100)
,(4, 'NameFour', DATEADD(mm, -1, GETDATE()), 123, 100)
,(5, 'NameFive', DATEADD(mm, -1, GETDATE()), 123, 100)
,(1, 'NameOne', DATEADD(mm, -5, GETDATE()), 123, 100)
,(3, 'NameThree', DATEADD(mm, -1, GETDATE()), 123, 100)
,(4, 'NameFour', DATEADD(mm, -1, GETDATE()), 123, 100)
,(5, 'NameFive', DATEADD(mm, -3, GETDATE()), 123, 100)
Feel free to ask any questions if I did not make this very clear :)
Related
I am working on a project and need to pull last 13 weeks of data. I have tried datediff in filter but it is pulling extra weeks. I have already set datefirst to 1 but still not getting desired result.
WHERE clause is
DATEDIFF(WEEK,dt.date_key,getdate())<=13
Try this code:
SELECT date_key FROM tbl WHERE date_key BETWEEN DATEADD(week, -13,GETDATE()) AND DATEADD(week, -1,GETDATE())
I have managed to get the answer. Put below in where clause and it has worked as expected.
d.date_key is my date column.
d.date_key >= DATEADD(dd, 0, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, GETDATE())) - 13, 0)) and d.date_key <= DATEADD(dd, 6, DATEADD(ww, DATEDIFF(ww, 0, DATEADD(dd, -1, GETDATE())) - 1, 0))
I am generating a case statement that will be a master shared dataset for our report date ranges since we frequently use the same date ranges. Currently I have previous week, previous month, previous year, current week, current month and current year. I would like to add our fiscal year which is (10/1 to 9/30) as well but I haven't been able to come up with a pure SQL way to do it.
DECLARE #frequency as nvarchar(20);
SET #frequency = 'CURRENT MONTH'
SELECT
CASE #frequency
WHEN 'PREVIOUS MONTH' THEN CONVERT(DATE,DATEADD(m,DATEDIFF(m,0,GETDATE())-1,0))
WHEN 'CURRENT MONTH' THEN CONVERT(DATE,DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(dd,-(DAY(GETDATE())-1),GETDATE()))))
WHEN 'CURRENT WEEK' THEN CONVERT(DATE,DATEADD(dd, 1, DATEDIFF(dd, 0,DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATETIME)))))
WHEN 'PREVIOUS WEEK' THEN CONVERT(DATE,DATEADD(dd, -6, DATEDIFF(dd, 0,DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATETIME)))))
WHEN 'CURRENT YEAR' THEN CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))
WHEN 'PREVIOUS YEAR' THEN CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) - 1, 0))
END as [START DATE],
CASE #frequency
WHEN 'PREVIOUS MONTH' THEN CONVERT(DATE,DATEADD(dd, 0, DATEDIFF(dd, 0,DATEADD(ms,-2,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)))))
WHEN 'CURRENT MONTH' THEN CONVERT(DATE,DATEADD(D, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) + 1, '19000101')))
WHEN 'CURRENT WEEK' THEN CONVERT(DATE,DATEADD(dd, 1, DATEDIFF(dd, 0,DATEADD(DAY, 7 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATETIME)))))
WHEN 'PREVIOUS WEEK' THEN CONVERT(DATE,DATEADD(dd, -6, DATEDIFF(dd, 0,DATEADD(DAY, 7 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATETIME)))))
WHEN 'CURRENT YEAR' THEN CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))))
WHEN 'PREVIOUS YEAR' THEN CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))))
END as [END DATE]
I've found the simplest way to perform this logic is to shift your date by the offset. If 10/1/2018 belongs to FY 2018, subtract the 9 months to convert the date to 1/1/2018. Then get the year value.
YEAR(DATEADD(MONTH,-9,'2018-09-01')) = 2017
YEAR(DATEADD(MONTH,-9,'2019-09-01')) = 2018
YEAR(DATEADD(MONTH,-9,[YourDateField]))
With this, you can also calculate the Fiscal Month
MONTH(DATEADD( month, -9, '2018-09-01 )) = 12
My company use the Year the FY ends, so 10/1/2018 would be part of the FY closing 2019. For my arrangement, I would need to add 3 months instead of subtract to get the calculation to come out right.
This approach leverages date math exclusively so should be able to use an index in most situations.
To find the given day for the datepart you're looking for, try this:
SELECT CurrentWeek = DATEADD( WEEK, DATEDIFF( WEEK, '2018-01-01', GETDATE()), '2018-01-01' ),
CurrentMonth = DATEADD( MONTH, DATEDIFF( MONTH, '2018-01-01', GETDATE()), '2018-01-01' ),
CurrentYear = DATEADD( YEAR, DATEDIFF( YEAR, '2018-01-01', GETDATE()), '2018-01-01' )
;
By basing the calculation on a seed date, you don't need to truncate the smaller time values.
According to your calculations, this will work:
DECLARE #frequency as nvarchar(20);
SET #frequency = 'FINANCIAL YEAR'
SELECT
CASE #frequency
WHEN 'FINANCIAL YEAR' THEN CONVERT(date, DATEADD(month, -1,
DATEADD(year, -1, DATEADD(month, -8, DATEADD(month, 13-MONTH(GETDATE()),
DATEDIFF(month, 0, GETDATE()), 0))))))
END as [START DATE],
CASE #frequency
WHEN 'FINANCIAL YEAR' THEN CONVERT(date, DATEADD(ms, -2,
DATEADD(month, -8, DATEADD(month, 13-MONTH(GETDATE()), DATEADD(month,
DATEDIFF(month, 0, GETDATE()), 0)))))
END as [END DATE];
Play with the -8 in order to change the financial year - e.g. if the finacial year if from 2017-03 to 2018-03, then it will be -9.
I hope that's helpful!
P.S. I used April (from 2017-04 to 2018-04) as financial year
I have a query that i have been tinkering with to use as a source for a report.
For some odd reason when i try to compare the output of datepart(dw,GetDate()) to an integer (2 for Monday) it gives me an error telling me incorrect syntax. i then started looking into why i couldn't compare two integers in an iif statement and... i have found absolutely no answers.
here is the full code (i went back and forth on how to do this, this is this iterations attempt)
DECLARE #dp integer,#d integer
set #dp =DATEpart(dw,GETDATE())
set #d = 2
SELECT TOP 100 PERCENT CUST_ORDER_LINE.PRODUCT_CODE
,CUSTOMER_ORDER.ID
,CUSTOMER_ORDER.CUSTOMER_ID
,CUST_ORDER_LINE.PART_ID
,CUST_ORDER_LINE.MISC_REFERENCE
,CUST_ORDER_LINE.COMMODITY_CODE
,CUSTOMER_ORDER.SALESREP_ID
,CUSTOMER_ORDER.TERRITORY
,CUST_ORDER_LINE.ORDER_QTY * CUST_ORDER_LINE.UNIT_PRICE AS Amount
,CUSTOMER_ORDER.ORDER_DATE
FROM CUST_ORDER_LINE
INNER JOIN CUSTOMER_ORDER ON CUST_ORDER_LINE.CUST_ORDER_ID = CUSTOMER_ORDER.ID
WHERE (
iif(#dp = #d,CUSTOMER_ORDER.ORDER_DATE BETWEEN ( dateadd(day, datediff(day, 0, getdate()), 0) - 3) AND ( dateadd(day, datediff(day, 0, getdate()),0))),
CUSTOMER_ORDER.ORDER_DATE BETWEEN ( dateadd(day, datediff(day, 0, getdate()), 0) - 1)) AND ( dateadd(day, datediff(day, 0, getdate()), + 1))))
)
ORDER BY CUSTOMER_ORDER.ORDER_DATE DESC
The point of this query is to pull data from yesterday, and Friday if it is Monday.
EDIT: error code Msg 170, Level 15, State 1, Line 19
Line 19: Incorrect syntax near '='.
IIF is in 2012. You can try using CASE instead.
DECLARE #dp integer,#d integer
set #dp =DATEpart(dw,GETDATE())
set #d = 2
SELECT TOP 100 PERCENT CUST_ORDER_LINE.PRODUCT_CODE
,CUSTOMER_ORDER.ID
,CUSTOMER_ORDER.CUSTOMER_ID
,CUST_ORDER_LINE.PART_ID
,CUST_ORDER_LINE.MISC_REFERENCE
,CUST_ORDER_LINE.COMMODITY_CODE
,CUSTOMER_ORDER.SALESREP_ID
,CUSTOMER_ORDER.TERRITORY
,CUST_ORDER_LINE.ORDER_QTY * CUST_ORDER_LINE.UNIT_PRICE AS Amount
,CUSTOMER_ORDER.ORDER_DATE
FROM CUST_ORDER_LINE
INNER JOIN CUSTOMER_ORDER ON CUST_ORDER_LINE.CUST_ORDER_ID = CUSTOMER_ORDER.ID
WHERE
CUSTOMER_ORDER.ORDER_DATE BETWEEN CASE
WHEN #dp = #d THEN ( dateadd(day, datediff(day, 0, getdate()), 0) - 3)
ELSE ( dateadd(day, datediff(day, 0, getdate()), 0) - 1)
END
AND CASE
WHEN #dp = #d THEN ( dateadd(day, datediff(day, 0, getdate()),0))
ELSE ( dateadd(day, datediff(day, 0, getdate()), + 1))
END
ORDER BY CUSTOMER_ORDER.ORDER_DATE DESC
I need to round to NEAREST start of month (in timestamp format) from a timestamp column.
How do one accomplish this?
Examples:
TimestampColumn A: Rounded to these values
2012-01-07 18:18:29.923 2012-01-01 00:00:00.000
2012-01-14 12:58:13.122 2012-01-01 00:00:00.000
2012-06-09 17:10:30.787 2012-06-01 00:00:00.000
2012-05-31 09:29:43.870 2012-06-01 00:00:00.000
2012-10-22 12:09:47.067 2012-11-01 00:00:00.000
2012-10-15 04:35:11.013 2012-10-01 00:00:00.000
Consider converting to date first
DECLARE #d DATETIME
set #d = CONVERT(DATE, '2012-02-14 12:58:13.122')
SET #d = DATEADD(DAY, 1-datepart(day, #d), #d)
SELECT #d
Here is one way to do it - just subtract all the parts of the date which you don't care about:
DECLARE #d DATETIME
set #d = '2012-02-14 12:58:13.122'
SET #d = DATEADD(DAY, 1-datepart(day, #d), #d)
SET #d = DATEADD(hour, -datepart(hour, #d), #d)
SET #d = DATEADD(minute, -datepart(minute, #d), #d)
SET #d = DATEADD(second, -datepart(second, #d), #d)
SET #d = DATEADD(millisecond, -datepart(millisecond, #d), #d)
SELECT #d
Calculate the length of the applicable month in seconds and then decide whether you are past the middle of the month. Go forward or back as needed.
declare #Foo as DateTime = '2012-10-15 12:35:11.013'
select
DateAdd( month, DateDiff( m, 0, #Foo ), 0 ) as 'Year/Month',
DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0), #Foo ) as 'Seconds Into Month',
DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0 ), DateAdd( month, DateDiff( m, 0, #Foo ) + 1, 0 ) ) as 'Seconds In Month',
DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0 ), DateAdd( month, DateDiff( m, 0, #Foo ) + 1, 0 ) ) / 2 as 'Seconds In Half Month',
DateAdd( month, DateDiff( m, 0, #Foo ) + Round( 1.0 * DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0), #Foo ) / DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0 ), DateAdd( month, DateDiff( m, 0, #Foo ) + 1, 0 ) ), 0 ), 0 ) as 'Rounded Date'
Thanks for contributing. But I'm going for this one; its good enough.
SELECT CASE
WHEN DATEDIFF(DAY, GETDATE(), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)) >
ABS(DATEDIFF(DAY, GETDATE(), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)))
THEN DATEADD(dd, datediff(dd, 0, DATEADD(DAY, DATEDIFF(DAY, GETDATE(), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)), GETDATE() ) )+0, 0)
ELSE dateadd(dd, datediff(dd, 0, DATEADD(DAY, DATEDIFF(DAY, GETDATE(), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)), GETDATE() ) )+0, 0)
END
Here is an example. You have 5 fields: the date you want to convert, the converted date as you wanted, the first day of the month, the last day of the month, and the first day of the next month.
Just choose what you need in it:
SELECT
BED_Meeting_When,
CASE WHEN DAY(BED_Meeting_When) < 15 THEN (DATEADD(DAY, (-DAY(BED_Meeting_When) + 1), BED_Meeting_When)) ELSE DATEADD(DAY, (-DAY(BED_Meeting_When) + 1), DATEADD(MONTH, 1, BED_Meeting_When)) END,
DATEADD(DAY, (-DAY(BED_Meeting_When) + 1), BED_Meeting_When) AS 'Arrondi au premier du mois',
DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, BED_Meeting_When) + 1, 0)) AS 'Arrondi au dernier du mois',
DATEADD(DAY, (-DAY(BED_Meeting_When) + 1), DATEADD(MONTH, 1, BED_Meeting_When)) AS 'Arrondi au premier du mois suivant',
BEMR_Titre
FROM bpri_entretien_detail
INNER JOIN bpri_entretien_motif ON (BED_BEMR_Idx = BEMR_Idx)
Hi I know this is late to the party a little simple offering can never offend I hope
Creating a mini temp table I pop'd the dates offered in the original post
and then selected from it as below
create table #DT(
TS_A datetime, TS_B datetime)
insert into #DT (ts_a) values ('2012-01-07 18:18:29.923'),
('2012-01-14 12:58:13.122'),
('2012-06-09 17:10:30.787'),
('2012-05-31 09:29:43.870'),
('2012-10-22 12:09:47.067'),
('2012-10-15 04:35:11.013')
select TS_A, DATEADD(MONTH, DATEDIFF(MONTH, 0,ts_a), 0) TS_B from #DT
Results - I hope this is clear
RESULTS
Amazing how times they are a changing :-)
TX
I hope this turns out alright haven't posted any where for over a decade
I am using SSRS 2008 and i have a stored proc which currently uses cursors to delete and add data, but even after I convert this to select queries, I am getting error:
Msg 102, Level 15, State 1, Line 39
Incorrect syntax near ')'.
Here was the original Cursor which worked:
OPEN PARTS
FETCH PARTS INTO #PART_NUM,
#PART_DESC
SET #PARTS_FETCH = ##FETCH_STATUS
WHILE #PARTS_FETCH = 0 BEGIN
SET #THE_DATE = dateadd("yy", -1, dateadd("m", -1, getdate()))
SET #END_DATE = DATEADD(ms, -5, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
-- Get PL for part number
Delete from #tbl_PL
Insert #tbl_PL
SELECT FRUD.tblXref.product_code FROM FRUD.tblfieldOrderablePart INNER JOIN
FRUD.MAX_APPROVED ON FRUD.tblfieldOrderablePart.fop_no = FRUD.MAX_APPROVED.fop_no AND
FRUD.tblfieldOrderablePart.fop_revision = FRUD.MAX_APPROVED.MaxOffop_revision INNER JOIN
FRUD.tblXref ON FRUD.MAX_APPROVED.fop_no = FRUD.tblXref.fop_no AND
FRUD.MAX_APPROVED.MaxOffop_revision = FRUD.tblXref.fop_revision
WHERE (dbo.FORMAT_PART(FRUD.tblfieldOrderablePart.fop_no) = dbo.FORMAT_PART(#PART_NUM))
-- End Get PL
WHILE #THE_DATE <= #END_DATE BEGIN
SET #THE_DATE = DATEADD(ms, -5, DATEADD(mm, DATEDIFF(m, 0, #THE_DATE) + 1, 0))
-- Get census using PL
SELECT #ALL_TOTAL = SUM(TheSum) FROM (SELECT CAST(RELIABILITY.Census.Census AS DECIMAL(9,2)) AS TheSum, (CONVERT(datetime, LEFT(CONVERT(char, Period), 4) + '-' + RIGHT(Period, 2) + '-1', 102)) as ThePeriod
FROM RELIABILITY.Census
WHERE RELIABILITY.Census.PL In (Select distinct * FROM #tbl_PL)
AND (CONVERT(datetime, LEFT(CONVERT(char, Period), 4) + '-' + RIGHT(Period, 2) + '-1', 102) >=
DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0)) AND (CONVERT(datetime, LEFT(CONVERT(char, Period), 4)
+ '-' + RIGHT(Period, 2) + '-1', 102) <= #THE_DATE) UNION ALL SELECT CAST(Census AS DECIMAL(9,2)) AS TheSum, Period FROM [MANUAL].SMARTSOLVE_CENSUS WHERE (Period >= DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0) AND Period <= #THE_DATE) AND (PL In (Select distinct * FROM #tbl_PL)))A
And here is my conversion to Select:
DECLARE #THE_DATE datetime,
#END_DATE datetime,
#THE_GOAL decimal(18,2),
#PART_NUM nvarchar(50),
#UNCHANGED_PART_NUM nvarchar(50),
#PART_DESC varchar(35),
#PARTS_FETCH int,
#NUM_FAILED int,
#AVG_CENSUS decimal(18,2),
#PL_VAR nvarchar(50),
#PL_FETCH int,
#PL_TOTAL decimal(9,2),
#ALL_TOTAL decimal(9,2)
--WHILE #PARTS_FETCH = 0 BEGIN
SET #THE_DATE = dateadd("yy", -1, dateadd("m", -1, getdate()))
SET #END_DATE = DATEADD(ms, -5, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
--WHILE #THE_DATE <= #END_DATE BEGIN
SET #THE_DATE = DATEADD(ms, -5, DATEADD(mm, DATEDIFF(m, 0, #THE_DATE) + 1, 0))
-- Get census using PL
SELECT #ALL_TOTAL = SUM(TheSum) FROM
(SELECT CAST(RELIABILITY.Census.Census AS DECIMAL(9,2)) AS TheSum
from RELIABILITY.Census
WHERE RELIABILITY.Census.PL In (Select distinct * FROM #tbl_PL)
AND (CONVERT(datetime, LEFT(CONVERT(char, Period), 4) + '-' + RIGHT(Period, 2) + '-1', 102) >=
DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0)) AND (CONVERT(datetime, LEFT(CONVERT(char, Period), 4)+ '-' + RIGHT(Period, 2) + '-1', 102) <= #THE_DATE)
UNION ALL
SELECT CAST(Census AS DECIMAL(9,2)) AS TheSum, Period
FROM [MANUAL].SMARTSOLVE_CENSUS
WHERE (Period >= DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0) AND Period <= #THE_DATE) AND (PL In (Select distinct * FROM #tbl_PL))
))A
As Joel and Lamak pointed out you have an extra ) This is actually really easy to find if you use something like Instant SQL formatter This will give the error
)(11,3) expected token:Unknown
)(11,3) expected token:
It also formats the SQL as below which makes it a little easier to follow.
SELECT #ALL_TOTAL = SUM(thesum)
FROM (SELECT CAST(reliability.census.census AS DECIMAL(9, 2)) AS thesum
FROM reliability.census
WHERE reliability.census.pl IN (SELECT DISTINCT *
FROM #tbl_pl)
AND ( CONVERT(DATETIME, LEFT(CONVERT(CHAR, period), 4) + '-' +
RIGHT(
period, 2)
+
'-1'
, 102) >= Dateadd(mm, Datediff(mm, 0, #THE_DATE) - 5, 0) )
AND ( CONVERT(DATETIME, LEFT(CONVERT(CHAR, period), 4)+ '-' +
RIGHT(
period, 2) +
'-1',
102) <= #THE_DATE )
UNION ALL
SELECT CAST(census AS DECIMAL(9, 2)) AS thesum,
period
FROM [MANUAL].smartsolve_census
WHERE ( period >= Dateadd(mm, Datediff(mm, 0, #THE_DATE) - 5, 0)
AND period <= #THE_DATE )
AND ( pl IN (SELECT DISTINCT *
FROM #tbl_pl) ))a
Sounds like you have mis-matched parentheses, double check and make sure they all line up correctly. You have one more ")" at the end of that last select statement than you have ever being opened. That's a lot of nesting! Make sure everything matches up how you intended, or you may get unexpected results if your UNION gets applied at the wrong level or something.
If I'm reading your query correctly, you have two errors. The first is an extra ")" on the last line, it should be:
WHERE (Period >= DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0) AND Period <= #THE_DATE) AND (PL In (Select distinct * FROM #tbl_PL))
) A
And, I think you also have more columns on your query after the UNION ALL, you are selecting CAST(Census AS DECIMAL(9,2)) AS TheSum, Period and on the first one you are selecting only one column: CAST(RELIABILITY.Census.Census AS DECIMAL(9,2)) AS TheSum