SQL / SSRS: The multi-part identifier " " could not be bound - sql

Working on a report that currently is in two columns on two datasets, an dam trying to combine the datasets into one single query. When I do the following query, I get The multi-part identifier "fa.InternalUserID" could not be bound.
--TST Group
SELECT A.AuditID,
A.FileID,
A.Description,
A.UserID,
IU.FirstName + ' ' + IU.LastName AS UserName,
FM.FileNumber,
SWITCHOFFSET(CONVERT(datetimeoffset, A.Date),'-05:00') AS 'LocalDateTime',
CONVERT(VARCHAR(10), A.Date, 101) AS 'Date',
CONVERT(VARCHAR(10), A.Date, 14) AS 'UnadjustedTime',
COUNT(FA.FileActionsID) AS ActionCount
FROM FileMain fm
INNER JOIN InternalUser AS IU ON fa.InternalUserID = IU.InternalUserID
JOIN FileActions FA on FA.FileID = FM.FileID
LEFT OUTER JOIN Audit AS A ON A.FileID = FM.FileID
WHERE (FM.OfficeID = 1)
AND (A.Description = 'File Opened'
OR A.Description = 'File Closed')
AND (A.Date >= GETDATE() - 2)
AND (IU.InternalUserID IN
(
--ID's go here
)
)
ORDER BY UserName, A.AuditID
Here are the original two queries I am combining:
--TST Group
SELECT A.AuditID,
A.FileID,
A.Description,
A.UserID,
IU.FirstName + ' ' + IU.LastName AS UserName,
FM.FileNumber,
SWITCHOFFSET(CONVERT(datetimeoffset, A.Date),'-05:00') AS 'LocalDateTime',
CONVERT(VARCHAR(10), A.Date, 101) AS 'Date',
CONVERT(VARCHAR(10), A.Date, 14) AS 'UnadjustedTime',
COUNT(FA.FileActionsID) AS ActionCount
FROM Audit AS A
INNER JOIN InternalUser AS IU ON A.UserID = IU.InternalUserID
LEFT OUTER JOIN FileMain AS FM ON A.FileID = FM.FileID
WHERE (FM.OfficeID = 1)
AND (A.Description = 'File Opened'
OR A.Description = 'File Closed')
AND (A.Date >= GETDATE() - 2)
AND (IU.InternalUserID IN
(
--ID's Go here
)
)
ORDER BY UserName, A.AuditID
and
SELECT IU.FirstName AS NAME,
COUNT(FA.FileActionsID) AS ActionCount
FROM FileActions AS FA
INNER JOIN InternalUser AS IU ON FA.ReceivedUserID = IU.InternalUserID
WHERE (FA.ReceivedDate > GETDATE() - 0)
AND (FA.ReceivedUserID IN (
--ID's go here
)
)
GROUP BY IU.FirstName

You have your joins in the wrong order. Currently you are trying to join InternalUser and FileActions when you've only mentioned FileMain and InternalUser (in that order) - you can't specify a condition against a table that hasn't been introduced to the join yet:
FROM FileMain fm
INNER JOIN InternalUser AS IU ON fa.InternalUserID = IU.InternalUserID
JOIN FileActions FA on FA.FileID = FM.FileID
LEFT OUTER JOIN Audit AS A ON A.FileID = FM.FileID
Should be (with obligatory schema prefixes added):
FROM dbo.FileMain fm
INNER JOIN dbo.FileActions FA on FA.FileID = FM.FileID
INNER JOIN dbo.InternalUser AS IU ON FA.InternalUserID = IU.InternalUserID
LEFT OUTER JOIN dbo.Audit AS A ON A.FileID = FM.FileID

Related

Optimizing Multiple SQL Queries

I have 2 queries that I want to optimize but I don't know how. The execution time is not acceptable for me.
I'm working with jira database and did query to show different tasks with some attributes.
The code is:
SET NOCOUNT ON
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка'
,p.[pname] AS 'П'
,users.[display_name] AS 'Исполнитель'
,CAST(ji.[CREATED] AS smalldatetime) AS 'Создан'
,CAST(ji.[RESOLUTIONDATE] AS smalldatetime) AS 'Дата резолюции'
,ji.[issuenum]
INTO #TT
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON (p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] as users ON (users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND itype.pname = 'Incident'
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,system_t.[NAME] AS 'Контур ИС'
,system_t_t.[NAME] AS 'Критичность системы'
INTO #TT1
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t ON (system_t.[ID] = substring(customfv.[STRINGVALUE], PatIndex('%[0-9]%', customfv.[STRINGVALUE]), len(customfv.[STRINGVALUE])))
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR] AS system_attr ON (system_t.[ID] = system_attr.[OBJECT_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR_VAL] AS system_attr_val ON (system_attr.[ID] = system_attr_val.[OBJECT_ATTRIBUTE_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t_t ON (system_attr_val.[REFERENCED_OBJECT_ID] = system_t_t.[ID])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND (customfv.[CUSTOMFIELD] = 21003 OR customfv.[CUSTOMFIELD] = 21005)
AND (system_t.[OBJECT_TYPE_ID] = 136 OR system_t.[OBJECT_TYPE_ID] = 303 OR system_t.[OBJECT_TYPE_ID] = 143)
AND system_attr.[OBJECT_TYPE_ATTRIBUTE_ID] = 461
AND itype.pname = 'Incident'
SELECT ji.[issuenum]
,pr_pr.[pname] AS '(project) Project'
INTO #TT2
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [project] AS pr_pr ON (pr_pr.[ID] = CAST(customfv.[NUMBERVALUE] AS BIGINT))
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND pr_pr.[pname] is not NULL
SELECT CTE.[Ключ], CTE.[Ссылка], CTE.[П], CTE.[Исполнитель], CTE.[Создан], CTE.[Дата резолюции], CTE2.[(project) Project], CTE1.[Контур ИС], CTE1.[Критичность системы], CTE.[issuenum]
FROM #TT CTE
LEFT OUTER JOIN #TT1 CTE1 ON (CTE1.[Ключ] = CTE.[Ключ])
LEFT OUTER JOIN #TT2 CTE2 ON (CTE2.[issuenum] = CTE.[issuenum])
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
There will be some information for the month before last.
summary of query
The next query is:
WITH CTE AS (
SELECT concat(p.pkey,'-',i.issuenum) AS 'Ключ',
cf.cfname,
cv.textvalue,
ROW_NUMBER() OVER (PARTITION BY i.issuenum ORDER BY i.issuenum) AS RowNumber_SLA
FROM customfield cf,
customfieldvalue cv,
jiraissue i,
project p
WHERE i.project = p.id
AND cv.issue = i.id
AND cv.customfield = cf.id
AND cf.customfieldtypekey = 'com.atlassian.servicedesk:sd-sla-field'
and i.issuenum IN ()
and CHARINDEX('"succeeded":false', TEXTVALUE) >0
)
SELECT CTE.Ключ
FROM CTE
WHERE RowNumber_SLA = 1
The goal is to get tasks where SLA has been failed.
So in and i.issuenum IN () my Python script is putting issue numbers that I got through previous query.
The average execution time is 3 minutes.
So, I want optimize this too, maybe join first query.
Sorry for my English. I'm not an English-speaking person.
P. S. Changing CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done' to ci.[NEWSTRING] = 'Done' causing the error The data types ntext and varchar are incompatible in the equal to operator. Workaround - ci.[NEWSTRING] LIKE 'Done' fixing this.
The first query must be rewrite as :
SELECT DISTINCT
concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ',
concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка',
p.[pname] AS 'П',
users.[display_name] AS 'Исполнитель',
CAST(ji.[CREATED] AS SMALLDATETIME) AS 'Создан',
CAST(ji.[RESOLUTIONDATE] AS SMALLDATETIME) AS 'Дата резолюции',
ji.[issuenum]
INTO #TT
FROM [jiraissue] AS ji
INNER JOIN [changegroup] AS cg ON(cg.[issueid] = ji.[id])
INNER JOIN [changeitem] AS ci ON(ci.[groupid] = cg.[id])
AND ci.FIELDTYPE = 'jira'
AND ci.FIELD = 'status'
LEFT OUTER JOIN [app_user] AS au ON(au.[user_key] = cg.[AUTHOR])
INNER JOIN [issuetype] AS itype ON(itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON(p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON(pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] AS users ON(users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(DATETIME, '2021-12-01')
AND cg.[CREATED] <= CONVERT(DATETIME, '2022-01-01')
AND ci.[NEWSTRING] = 'Done'
AND itype.pname = 'Incident';
False outer joins are converted in INNER and I have aslo eliminate the ugly CONVERT to NVARCHAR(max)
Same troubles appears in the second query...

How to add IF ELSE by referencing to previous value

I am trying to read my previous value of "OPENSEATING" and store it into the variable #OPENSEATING. For the second query I want it to check first the value of #OPENSEATING if match condition do the below query.
i believe my declaration is correct, is there any syntax error?
DECLARE #OPENSEATING AS BIT
SELECT
'2019-01-31' AS DATE,
(SELECT
THEATRES.OPENSEATING
FROM
SEAT LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES AS B ON THEATRES.ID = B.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND B.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
B.ID = A.ID
GROUP BY THEATRES.OPENSEATING) AS #OPENSEATING,
IF(#OPENSEATING =0)
BEGIN
(SELECT
(THEATRES.CAPACITY - COUNT(TICKET_ITEMS.ID)) AS SEATREMAINING
FROM
SEAT LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES ON THEATRES.ID = SHOWTIMES.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND SHOWTIMES.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
SHOWTIMES.ID = A.ID
GROUP BY THEATRES.CAPACITY) AS REMAININGSEAT
END
ELSE IF(#OPENSEATING =1)
BEGIN
(SELECT
(THEATRES.CAPACITY - COUNT(TICKET_ITEMS.ID)) AS SEATREMAINING
FROM
SHOWTIMES LEFT JOIN THEATRES ON THEATRES.ID = SHOWTIMES.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND SHOWTIMES.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
SHOWTIMES.ID = A.ID
GROUP BY THEATRES.CAPACITY) AS REMAININGSEAT
END
SHOWSCHEDULES.ID AS SHOWSCHEDULE_ID,
A.ID AS SHOWTIME_ID,
A.THEATREID
FROM
SHOWSCHEDULES JOIN SHOWTIMES AS A ON SHOWSCHEDULES.ID = A.SHOWSCHEDULEID
JOIN SHOWLANGUAGES ON A.SHOWLANGUAGEID = SHOWLANGUAGES.ID
WHERE
'2019-01-31' BETWEEN CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWFROMDATE, 20) AND CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWTODATE, 20)
AND CONVERT(VARCHAR(8), getdate(), 8) < CONVERT(VARCHAR(10), A.SHOWENDTIME,8)
ORDER BY SHOWBEGINTIME_24 ASC
;
AS SUGGESTED BY #Slava Murygin I tried creating CTE TABLE as below but even this is showing error, what is wrong with my simple cte table. The inner query is working fine.
WITH cte_name (OPENSEATING) AS (
SELECT
(SELECT
THEATRES.OPENSEATING
FROM
SEAT LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES AS B ON THEATRES.ID = B.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND B.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
B.ID = A.ID
GROUP BY THEATRES.OPENSEATING) AS OPENSEATING
FROM
SHOWSCHEDULES JOIN SHOWTIMES AS A ON SHOWSCHEDULES.ID = A.SHOWSCHEDULEID
JOIN SHOWLANGUAGES ON A.SHOWLANGUAGEID = SHOWLANGUAGES.ID
WHERE
'2019-01-31' BETWEEN CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWFROMDATE, 20) AND CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWTODATE, 20)
AND CONVERT(VARCHAR(8), getdate(), 8) < CONVERT(VARCHAR(10), A.SHOWENDTIME,8)
)
I have made changes to your CTE as:
WITH cte_name (OPENSEATING) AS (
SELECT
THEATRES.OPENSEATING as OPENSEATING
FROM
SEAT LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES AS B ON THEATRES.ID = B.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND B.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
B.ID = A.ID
GROUP BY THEATRES.OPENSEATING
)
select openseating from
cte_name, SHOWSCHEDULES JOIN SHOWTIMES AS A ON SHOWSCHEDULES.ID = A.SHOWSCHEDULEID
JOIN SHOWLANGUAGES ON A.SHOWLANGUAGEID = SHOWLANGUAGES.ID
WHERE
'2019-01-31' BETWEEN CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWFROMDATE, 20) AND CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWTODATE, 20)
AND CONVERT(VARCHAR(8), getdate(), 8) < CONVERT(VARCHAR(10), A.SHOWENDTIME,8)
You can't do that in one query. You have to get variable in the first query and then use it in IF statement.
If you WANT to use ONLY ONE statement then you have to use CTEs, but it will hide the logic and will be hard to debug.
It might be something like this, but no guarantee it will work, because I have no idea about your business logic and data behind:
;WITH OPENSEATING as (
SELECT THEATRES.OPENSEATING, B.ID
FROM SEAT
LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES AS B ON THEATRES.ID = B.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND B.ID = TICKET_ITEMS.SHOWTIMESID
GROUP BY THEATRES.OPENSEATING),
REMAININGSEAT0 as (
SELECT st.ID, (t.CAPACITY - COUNT(ti.ID)) AS SEATREMAINING
FROM SEAT as s
LEFT JOIN THEATRES as t ON s.ROOMID = t.ID
LEFT JOIN SHOWTIMES as st ON t.ID = st.THEATREID
LEFT JOIN TICKET_ITEMS ON ti.SEATNO = s.SEATNO AND st.ID = ti.SHOWTIMESID
GROUP BY t.CAPACITY),
REMAININGSEAT1 as (
SELECT st.ID, (t.CAPACITY - COUNT(ti.ID)) AS SEATREMAINING
FROM SHOWTIMES as st
LEFT JOIN THEATRES as t ON t.ID = st.THEATREID
LEFT JOIN SEAT as s ON s.ROOMID = t.ID
LEFT JOIN TICKET_ITEMS as ti ON ti.SEATNO = s.SEATNO AND st.ID = ti.SHOWTIMESID
GROUP BY t.CAPACITY)
SELECT '2019-01-31' AS DATE
, ss.ID AS SHOWSCHEDULE_ID
, A.ID AS SHOWTIME_ID
, A.THEATREID
, SEATREMAINING = CASE OS.OPENSEATING WHEN 0 THEN RS0.SEATREMAINING ELSE RS1.SEATREMAINING END
FROM SHOWSCHEDULES as ss
INNER JOIN SHOWTIMES AS A ON ss.ID = A.SHOWSCHEDULEID
INNER JOIN SHOWLANGUAGES as SL ON A.SHOWLANGUAGEID = SL.ID
INNER JOIN OPENSEATING as OS ON OS.ID = A.ID
LEFT JOIN REMAININGSEAT0 as RS0 ON RS0.ID = A.ID
LEFT JOIN REMAININGSEAT1 as RS1 ON RS1.ID = A.ID
WHERE '2019-01-31' BETWEEN CONVERT(VARCHAR(10), ss.SHOWFROMDATE, 20) AND CONVERT(VARCHAR(10), ss.SHOWTODATE, 20)
AND CONVERT(VARCHAR(8), getdate(), 8) < CONVERT(VARCHAR(10), A.SHOWENDTIME,8)
ORDER BY SHOWBEGINTIME_24 ASC;

Query takes forever to output info - tips on optimization

I have a query that works awesomely - but - it takes about 10 minutes to load up. Which is insane. And I would like for it to run faster than it currently does now.
I was wondering if there were any tips I could take to optimize my query to make it run faster?
select DISTINCT
c.PaperID,
cdd.CodesF,
c.PageCount,
prr.projectname,
u.firstname + ' ' + u.lastname as Name,
ett.EventName,
cast(c.AssignedDate as DATE) [AssignedDate],
cast(ev.EventCompletionDate as DATE) [CompletionDate],
ar.ResultDescription,
a.Editor
from tbl_Papers c
left outer join (select cd.PaperId, count(*) as CodesF
from tbl_PaperCodes cd group by cd.PaperId) cdd
on cdd.PaperId = c.PaperId
left outer join
(SELECT
wfce.PaperEventActionNum,
c.PaperId,
CONVERT(varchar,wfce.ActionDate,101) CompletionDate,
pr.ProjectName,
wfce.ActionUserId,
u.firstname+' '+u.lastname [Editor]
FROM
dbo.tbl_WFPaperEventActions wfce
INNER JOIN dbo.tbl_Papers c ON wfce.PaperId = c.PaperId
INNER JOIN tbl_Providers p ON p.ProviderID = c.ProviderID
INNER JOIN tbl_Sites s ON s.SiteID = p.SiteID
INNER JOIN tbl_Projects pr ON s.ProjectId=pr.ProjectId
INNER JOIN tbl_Users u ON wfce.ActionUserId=u.UserId
WHERE
wfce.EventId = 204
AND c.Papersource =0
GROUP BY
wfce.PaperEventActionNum,
c.PaperId,
CONVERT(varchar,wfce.ActionDate,101),
pr.ProjectName,
wfce.ActionUserId,
u.firstname+' '+u.lastname
)a ON a.PaperId=c.PaperId,
tbl_Providers p, tbl_Sites s,
tbl_Projects prr, tbl_WFPaperEvents ev,
tbl_Users u, tbl_WFPaperEventTypes ett,
tbl_WFPaperEventActions arr, tbl_WFPaperEventActionResults ar
where s.SiteId = p.SiteId
and p.ProviderId = c.ProviderId
and s.ProjectId = prr.ProjectId
and ev.PaperId = c.PaperId
and ev.EventCreateUserId = u.UserId
and ev.EventCompletionDate >= dateadd(day,datediff(day,1,GETDATE()),0)
and ev.EventCompletionDate < dateadd(day,datediff(day,0,GETDATE()),0)
and ev.EventStatusId = 3
and ev.EventId in (201, 203)
and c.Papersource =0--Offshore
and ev.EventId=ett.EventID
and arr.PaperId=c.PaperId
and arr.EventId=ev.EventId
and arr.EventId=ar.EventID
and arr.ActionResultId=ar.ResultID
and arr.ActionResultId in (1,2,3,4)
order by paperid, u.FirstName + ' ' + u.LastName
You need to re-look carefully at every piece of this query and ask yourself, is that needed?
Take the subquery with alias a.
It joins 6 tables, but if you trace up to your final select clause only [Editor] is supplied from that alias. So do you need 6 tables to arrive at editor? No you don't in fact you only need 2 tbl_WFPaperEventActions and tbl_Users. Furthermore, this subquery is grouping by 6 items including a date, but 3 of those items are not used anywhere else in the overall query - so why go include these in the grouping? This allows us to drop 3 of the joined tables.
Of the remaining 3 grouping items a further 1 can be substituted to avoid the join between tbl_WFPaperEventActions and tbl_Papers because the join condition is "wfce.PaperId = c.PaperId", all we need then is to group by wfce.PaperId instead of c.PaperId
Finally we are then interested in the field wfce.PaperEventActionNum this is supplied by the subquery but isn't used in the larger query? Why provide that field is it isn't used? Well it turns out that it should be used to complete a join. The subquery aliased as a needs joining into the outer query on both PaperEventActionNum and PaperId. This by the way also requires that the whole subquery needs to be pushed down the joining structure to comply with ANSI join syntax rules.
Never "mix" ANSI join syntax with joins done "the old fashioned way"
This really is a recipe for a disaster.
Below I have "started" some amendments to your query, but I cannot really complete it as I have no way to test any part of it; and I don't know your data model at all.
Personally, I would re-start this query from scratch, starting lean and adding item by item to ensure it remains lean.
SELECT DISTINCT /* distinct isn't a good solution here */
c.PaperID
, cdd.CodesF
, c.PageCount
, prr.projectname
, u.firstname + ' ' + u.lastname AS Name
, ett.EventName
, CAST(c.AssignedDate AS date) [AssignedDate]
, CAST(ev.EventCompletionDate AS date) [CompletionDate]
, ar.ResultDescription
, a.Editor
FROM tbl_Papers c
LEFT OUTER JOIN ( -- can this be an inner join instead?
SELECT
cd.PaperId
, COUNT(*) AS CodesF
FROM tbl_PaperCodes cd
GROUP BY
cd.PaperId
) cdd
ON cdd.PaperId = c.PaperId
INNER JOIN tbl_Providers p ON c.ProviderId = p.ProviderId
INNER JOIN tbl_Sites s ON p.SiteId = s.SiteId
INNER JOIN tbl_Projects prr ON s.ProjectId = prr.ProjectId
INNER JOIN tbl_WFPaperEvents ev ON c.PaperId = ev.PaperId
INNER JOIN tbl_Users u ON ev.EventCreateUserId = u.UserId
INNER JOIN tbl_WFPaperEventTypes ett ON ev.EventId = ett.EventID
INNER JOIN tbl_WFPaperEventActions arr ON c.PaperId = arr.PaperId
AND ev.EventId = arr.EventId
INNER JOIN tbl_WFPaperEventActionResults ar ON arr.EventId = ar.EventID
AND arr.ActionResultId = ar.ResultID
AND arr.ActionResultId IN (1, 2, 3, 4)
LEFT OUTER JOIN (
SELECT
wfce.PaperEventActionNum
, wfce.PaperId
--, c.PaperId
--, CONVERT(varchar, wfce.ActionDate, 101) CompletionDate -- cast to date here
--, pr.ProjectName
--, wfce.ActionUserId
, u.firstname + ' ' + u.lastname [Editor]
FROM dbo.tbl_WFPaperEventActions wfce
--INNER JOIN dbo.tbl_Papers c ON wfce.PaperId = c.PaperId
--INNER JOIN tbl_Providers p ON p.ProviderID = c.ProviderID
--INNER JOIN tbl_Sites s ON s.SiteID = p.SiteID
--INNER JOIN tbl_Projects pr ON s.ProjectId = pr.ProjectId
tbl_Users INNER JOIN u ON wfce.ActionUserId = u.UserId
WHERE wfce.EventId = 204
AND c.Papersource = 0
GROUP BY
wfce.PaperEventActionNum
, wfce.PaperId
--, c.PaperId
--, CONVERT(varchar, wfce.ActionDate, 101)
--, pr.ProjectName
--, wfce.ActionUserId
, u.firstname + ' ' + u.lastname
) a
ON c.PaperId = a.PaperId AND arr.PaperEventActionNum = a.PaperEventActionNum
WHERE ev.EventCompletionDate >= DATEADD(DAY, DATEDIFF(DAY, 1, GETDATE()), 0)
AND ev.EventCompletionDate < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
AND ev.EventStatusId = 3
AND ev.EventId IN (201, 203)
AND c.Papersource = 0--Offshore
ORDER BY
paperid, u.FirstName + ' ' + u.LastName
I really do hate DISTINCT. It is nasty. It does not solve problems, it just hides them; AND slows down everything to do the hiding.
Use distinct in inverse proportion to query complexity:
if a query is really simple you can use distinct
If a query is complex do not use distinct
Check how many of fields on which you have join, where and group by clauses, have indexes. Every non-indexed field can negatively affect performance.
Calculated fields in GROUP BY are probably a pain, as well as DISTINCT (especially if they are not indexed). E.g. grouping on something like u.ID instead of u.firstname+' '+u.lastname or pr.ProjectId i/o pr.ProjectName should make things faster (you can sort the output according to the other criteria if needed).
Do you really need left join where you use it? I.e. do you want to keep the tables from the other side of the join even when there is no match on the other side? If not, replace it with inner join.
Various small improvements here, e.g.:
(assuming Papersource and EventId are indexes):
FROM
(SELECT * FROM dbo.tbl_WFPaperEventActions WHERE EventId = 204) wfce
INNER JOIN
(SELECT * FROM dbo.tbl_Papers WHERE Papersource = 0) c
ON wfce.PaperId = c.PaperId
INNER JOIN tbl_Providers p ON p.ProviderID = c.ProviderID
INNER JOIN tbl_Sites s ON s.SiteID = p.SiteID
INNER JOIN tbl_Projects pr ON s.ProjectId=pr.ProjectId
INNER JOIN tbl_Users u ON wfce.ActionUserId=u.UserId
instead of
FROM
dbo.tbl_WFPaperEventActions wfce
INNER JOIN dbo.tbl_Papers c ON wfce.PaperId = c.PaperId
INNER JOIN tbl_Providers p ON p.ProviderID = c.ProviderID
INNER JOIN tbl_Sites s ON s.SiteID = p.SiteID
INNER JOIN tbl_Projects pr ON s.ProjectId=pr.ProjectId
INNER JOIN tbl_Users u ON wfce.ActionUserId=u.UserId
WHERE
wfce.EventId = 204
AND c.Papersource =0
or (if I understood the idea correctly):
and ev.EventCompletionDate BETWEEN (
dateadd(day, -1, GETDATE()) and dateadd(ns, -1, GETDATE())
instead of:
and ev.EventCompletionDate >= dateadd(day,datediff(day,1,GETDATE()),0)
and ev.EventCompletionDate < dateadd(day,datediff(day,0,GETDATE()),0)
In general: ask yourself what exactly you want to achieve with this query, which parts of the data are relevant for it, how many of your source tables can be replaced with snippets from them (this can make JOINs work faster), and try to be consistent regarding the usage of JOIN and WHERE clauses.

Limiting a query by MTD, Prior month, etc. to SSRS

I am trying to form a report out of the following query, and the issue I am having is: how do I get it to make a structure where I can call it in SSRS, say calling MTF, PMonth, PPMonth as a "Type" choice, when I put it into SSRS, I want MTD, PMonth and PPMonth to appear in the report as separate entities.
-- ResWare.dbo.rptClosingPipeline3
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DECLARE #today varchar(20)
SET #today = Convert(varchar, GetDate(), 101)
DECLARE #startdate datetime
SET #startdate = dbo.GetUTCDateTimeFunc(DateAdd(m, 0, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))--
DECLARE #enddate datetime --today at midnight. first moment of the day
SET #enddate = dbo.GetUTCDateTimeFunc(#today)--
DECLARE #MTD datetime
SET #MTD = dbo.GetUTCDateTimeFunc(DateAdd(m, 0, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))--
DECLARE #PMonth datetime
SET #PMonth = dbo.GetUTCDateTimeFunc(DateAdd(m, -1, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))
DECLARE #PMonthEnd datetime
SET #PMonthEnd = dbo.GetUTCDateTimeFunc(DateAdd(m, 0, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))--
DECLARE #PPMonth datetime
SET #PPMonth = dbo.GetUTCDateTimeFunc(DateAdd(m, -2, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))
DECLARE #PPMonthEnd datetime
SET #PPMonthEnd = dbo.GetUTCDateTimeFunc(DateAdd(m, -1, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))--
SELECT FM.FileNumber AS FileNumber,
ISNULL(IU.TEAMNAME,'') AS Closer,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate) AS Scheduled,
dbo.GetLocalDateTimeFunc(FM.DisbursementDate) AS DisbursementDate,
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate) AS EstSettlementDate,
CASE WHEN EXISTS (SELECT * FROM FilePartnerRel FPR1
WHERE FPR1.PartnerTypeID = 10033 AND FPR1.FileID = FM.FileID)
THEN P.State+'-(W)'
ELSE P.State END AS State,
ISNULL(P.StreetNumber,'')+' '+ISNULL(P.StreetDirection,'')+' '+ISNULL(P.StreetName,'')+' '+ISNULL(P.Unit,'')AS PropertyAddress,
S.Name,
(SELECT CONVERT(varchar(7000),Body) FROM Note WHERE NoteID =
(Select MAX(N.NoteID)
FROM Note N
JOIN FileActions A1 ON A1.FileID=FM.FileID
AND A1.ActionDefID IN (141,386,306)
JOIN FileActionNoteRel AN ON AN.FileActionsID=A1.FileActionsID
AND N.NoteID = AN.NoteID)) AS Note,
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
JOIN Coordinator C1 ON C1.FileID = FA1.FileID
AND C1.CoordinatorTypeID IN (2, 6)
AND C1.CoordinatorID = C.CoordinatorID
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #startdate
AND FM1.StatusID != 8),
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #startdate
AND FM1.StatusID != 8) AS TotalDisb
, TRT.Name CurativeItem
, SD.CommitmentEffDate
FROM FileMain FM
JOIN ActionListTransactionType ALTT ON ALTT.ActionListTransactionTypeID = FM.ActionListTransactionTypeID
JOIN ActionListProductType ALPT ON ALPT.ActionListProductTypeID = FM.ActionListProductTypeID
JOIN Coordinator C ON C.FileID = FM.FileID
AND C.CoordinatorTypeID IN (2)
LEFT JOIN FilePartnerRel FPR ON FPR.FileID = FM.FileID
AND FPR.PartnerTypeID = 5
JOIN Property P ON P.FileID = FM.FileID
LEFT JOIN PartnerCompany PC ON PC.PartnerCompanyID = FPR.PartnerCompanyID
JOIN PartnerCompany PC1 ON PC1.PartnerCompanyID = FM.ClientID
JOIN TEAM IU ON IU.TEAMID = C.CoordinatorID
JOIN Status S ON S.StatusID = FM.StatusID
LEFT JOIN TitleReview TR ON TR.FileID = Fm.FileID
AND (TR.InternalClear IS NULL OR TR.InternalClear = 0)
LEFT JOIN TitleReviewType TRT ON TRT.TitleReviewTypeID = TR.TitleReviewTypeID
LEFT JOIN SearchData SD ON SD.FileID = FM.FileID
WHERE FM.OfficeID = 1
AND FM.FileNumber NOT LIKE 'PA-%'
AND FM.StatusID IN (2,4,5,10,11,14,15,18)
UNION ALL
SELECT FM.FileNumber AS FileNumber,
ISNULL(IU.TEAMNAME,'') AS Closer,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate) AS Scheduled,
dbo.GetLocalDateTimeFunc(FM.DisbursementDate) AS DisbursementDate,
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate) AS EstSettlementDate,
CASE WHEN EXISTS (SELECT * FROM FilePartnerRel FPR1
WHERE FPR1.PartnerTypeID = 10033 AND FPR1.FileID = FM.FileID)
THEN P.State+'-(W)'
ELSE P.State END AS State,
ISNULL(P.StreetNumber,'')+' '+ISNULL(P.StreetDirection,'')+' '+ISNULL(P.StreetName,'')+' '+ISNULL(P.Unit,'')AS PropertyAddress,
S.Name,
(SELECT CONVERT(varchar(7000),Body) FROM Note WHERE NoteID =
(Select MAX(N.NoteID)
FROM Note N
JOIN FileActions A1 ON A1.FileID=FM.FileID
AND A1.ActionDefID IN (141,386,306)
JOIN FileActionNoteRel AN ON AN.FileActionsID=A1.FileActionsID
AND N.NoteID = AN.NoteID)) AS Note,
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
JOIN Coordinator C1 ON C1.FileID = FA1.FileID
AND C1.CoordinatorTypeID IN (2, 6)
AND C1.CoordinatorID = C.CoordinatorID
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #MTD
AND FM1.StatusID != 8),
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #MTD
AND FM1.StatusID != 8) AS TotalDisb
, TRT.Name CurativeItem
, SD.CommitmentEffDate
FROM FileMain FM
JOIN ActionListTransactionType ALTT ON ALTT.ActionListTransactionTypeID = FM.ActionListTransactionTypeID
JOIN ActionListProductType ALPT ON ALPT.ActionListProductTypeID = FM.ActionListProductTypeID
JOIN Coordinator C ON C.FileID = FM.FileID
AND C.CoordinatorTypeID IN (2)
LEFT JOIN FilePartnerRel FPR ON FPR.FileID = FM.FileID
AND FPR.PartnerTypeID = 5
JOIN Property P ON P.FileID = FM.FileID
LEFT JOIN PartnerCompany PC ON PC.PartnerCompanyID = FPR.PartnerCompanyID
JOIN PartnerCompany PC1 ON PC1.PartnerCompanyID = FM.ClientID
JOIN TEAM IU ON IU.TEAMID = C.CoordinatorID
JOIN Status S ON S.StatusID = FM.StatusID
LEFT JOIN TitleReview TR ON TR.FileID = Fm.FileID
AND (TR.InternalClear IS NULL OR TR.InternalClear = 0)
LEFT JOIN TitleReviewType TRT ON TRT.TitleReviewTypeID = TR.TitleReviewTypeID
LEFT JOIN SearchData SD ON SD.FileID = FM.FileID
WHERE FM.OfficeID = 1
AND FM.FileNumber NOT LIKE 'PA-%'
AND FM.StatusID IN (2,4,5,10,11,14,15,18)
UNION ALL
SELECT FM.FileNumber AS FileNumber,
ISNULL(IU.TEAMNAME,'') AS Closer,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate) AS Scheduled,
dbo.GetLocalDateTimeFunc(FM.DisbursementDate) AS DisbursementDate,
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate) AS EstSettlementDate,
CASE WHEN EXISTS (SELECT * FROM FilePartnerRel FPR1
WHERE FPR1.PartnerTypeID = 10033 AND FPR1.FileID = FM.FileID)
THEN P.State+'-(W)'
ELSE P.State END AS State,
ISNULL(P.StreetNumber,'')+' '+ISNULL(P.StreetDirection,'')+' '+ISNULL(P.StreetName,'')+' '+ISNULL(P.Unit,'')AS PropertyAddress,
S.Name,
(SELECT CONVERT(varchar(7000),Body) FROM Note WHERE NoteID =
(Select MAX(N.NoteID)
FROM Note N
JOIN FileActions A1 ON A1.FileID=FM.FileID
AND A1.ActionDefID IN (141,386,306)
JOIN FileActionNoteRel AN ON AN.FileActionsID=A1.FileActionsID
AND N.NoteID = AN.NoteID)) AS Note,
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
JOIN Coordinator C1 ON C1.FileID = FA1.FileID
AND C1.CoordinatorTypeID IN (2, 6)
AND C1.CoordinatorID = C.CoordinatorID
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #PMonth
AND FM1.StatusID != 8),
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #PMonth
AND FM1.StatusID != 8) AS TotalDisb
, TRT.Name CurativeItem
, SD.CommitmentEffDate
FROM FileMain FM
JOIN ActionListTransactionType ALTT ON ALTT.ActionListTransactionTypeID = FM.ActionListTransactionTypeID
JOIN ActionListProductType ALPT ON ALPT.ActionListProductTypeID = FM.ActionListProductTypeID
JOIN Coordinator C ON C.FileID = FM.FileID
AND C.CoordinatorTypeID IN (2)
LEFT JOIN FilePartnerRel FPR ON FPR.FileID = FM.FileID
AND FPR.PartnerTypeID = 5
JOIN Property P ON P.FileID = FM.FileID
LEFT JOIN PartnerCompany PC ON PC.PartnerCompanyID = FPR.PartnerCompanyID
JOIN PartnerCompany PC1 ON PC1.PartnerCompanyID = FM.ClientID
JOIN TEAM IU ON IU.TEAMID = C.CoordinatorID
JOIN Status S ON S.StatusID = FM.StatusID
LEFT JOIN TitleReview TR ON TR.FileID = Fm.FileID
AND (TR.InternalClear IS NULL OR TR.InternalClear = 0)
LEFT JOIN TitleReviewType TRT ON TRT.TitleReviewTypeID = TR.TitleReviewTypeID
LEFT JOIN SearchData SD ON SD.FileID = FM.FileID
WHERE FM.OfficeID = 1
AND FM.FileNumber NOT LIKE 'PA-%'
AND FM.StatusID IN (2,4,5,10,11,14,15,18)
UNION ALL
SELECT FM.FileNumber AS FileNumber,
ISNULL(IU.TEAMNAME,'') AS Closer,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate) AS Scheduled,
dbo.GetLocalDateTimeFunc(FM.DisbursementDate) AS DisbursementDate,
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate) AS EstSettlementDate,
CASE WHEN EXISTS (SELECT * FROM FilePartnerRel FPR1
WHERE FPR1.PartnerTypeID = 10033 AND FPR1.FileID = FM.FileID)
THEN P.State+'-(W)'
ELSE P.State END AS State,
ISNULL(P.StreetNumber,'')+' '+ISNULL(P.StreetDirection,'')+' '+ISNULL(P.StreetName,'')+' '+ISNULL(P.Unit,'')AS PropertyAddress,
S.Name,
(SELECT CONVERT(varchar(7000),Body) FROM Note WHERE NoteID =
(Select MAX(N.NoteID)
FROM Note N
JOIN FileActions A1 ON A1.FileID=FM.FileID
AND A1.ActionDefID IN (141,386,306)
JOIN FileActionNoteRel AN ON AN.FileActionsID=A1.FileActionsID
AND N.NoteID = AN.NoteID)) AS Note,
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
JOIN Coordinator C1 ON C1.FileID = FA1.FileID
AND C1.CoordinatorTypeID IN (2, 6)
AND C1.CoordinatorID = C.CoordinatorID
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #PPMonth
AND FM1.StatusID != 8),
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #PPMonth
AND FM1.StatusID != 8) AS TotalDisb
, TRT.Name CurativeItem
, SD.CommitmentEffDate
FROM FileMain FM
JOIN ActionListTransactionType ALTT ON ALTT.ActionListTransactionTypeID = FM.ActionListTransactionTypeID
JOIN ActionListProductType ALPT ON ALPT.ActionListProductTypeID = FM.ActionListProductTypeID
JOIN Coordinator C ON C.FileID = FM.FileID
AND C.CoordinatorTypeID IN (2)
LEFT JOIN FilePartnerRel FPR ON FPR.FileID = FM.FileID
AND FPR.PartnerTypeID = 5
JOIN Property P ON P.FileID = FM.FileID
LEFT JOIN PartnerCompany PC ON PC.PartnerCompanyID = FPR.PartnerCompanyID
JOIN PartnerCompany PC1 ON PC1.PartnerCompanyID = FM.ClientID
JOIN TEAM IU ON IU.TEAMID = C.CoordinatorID
JOIN Status S ON S.StatusID = FM.StatusID
LEFT JOIN TitleReview TR ON TR.FileID = Fm.FileID
AND (TR.InternalClear IS NULL OR TR.InternalClear = 0)
LEFT JOIN TitleReviewType TRT ON TRT.TitleReviewTypeID = TR.TitleReviewTypeID
LEFT JOIN SearchData SD ON SD.FileID = FM.FileID
WHERE FM.OfficeID = 1
AND FM.FileNumber NOT LIKE 'PA-%'
AND FM.StatusID IN (2,4,5,10,11,14,15,18)
GROUP BY FM.FileNumber,
PC1.Name,
PC.Name,
ISNULL(IU.TEAMNAME,''),
ALTT.Name +': '+ALPT.DisplayName,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate),
dbo.GetLocalDateTimeFunc(FM.DisbursementDate),
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate),
FM.FileID,
P.State,
P.StreetNumber,
P.StreetDirection,
P.StreetName,
P.Unit,
S.Name,
FM.EstSettlementDate,
C.CoordinatorID,
TRT.Name,
SD.CommitmentEffDate
Option 1:
Add a hard-coded column to your query as follows:
SELECT ...
, 'StartDt' as Period
From QUERY1
UNION ALL
SELECT ...
, 'MTD' as Period
FROM QUERY2
UNION ALL
SELECT ...
, 'Pmonth' as Period
FROM QUERY3
Then I would add a report parameter "#filter" (or whatever name you like) with the 'StartDt', 'MTD', 'Pmonth', etc. as its available values. Enable multiple values and ensure it is a text parameter.
Then set each section of your report's filter to see if the "Period" column matches the parameter.value of the filter.
Option 2:
Add a report parameter #filter as above.
Create a table variable and insert the values passed in by the filter parameter into it.
Use a Case When to pass a 1 or 0 back to SSRS in the final column, representing whether that section should be visible or not.
,Period = CASE
WHEN 'StartDt' IN (SELECT * FROM #table) then 1
ELSE 0
END
Then set your filter to only include data with a period value of 1 and to set the visibility of the report sections accordingly.

Error while using the Group By Clause

I am getting the sql server error "the text ntext and image data types cannot be compared or sorted except when using is null or like" while executing
SELECT r.Shift, l.lab_title AS [Assigned Lab], u.user_name AS [L/A],
CONVERT(varchar(100), t.Time) + ' To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM table_roaster_time_table AS r
INNER JOIN table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId
INNER JOIN table_user AS u ON r.user_id = u.user_id
INNER JOIN table_labs AS l ON r.lab_id = l.lab_id
INNER JOIN table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY r.Shift, l.lab_title, u.user_name
Don't know what's the problem. I have used aggregate function also with it, just for formality but it's not working.
I'm guessing your r.Shift column is a text or ntext type. Because of this it cannot be used in a group by
One option might be to use a CAST on the suspect column, but you might loose data. Example:
SELECT r.Shift, l.lab_title AS [Assigned Lab], u.user_name AS [L/A], CONVERT(varchar(100), t.Time) + ' To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM table_roaster_time_table AS r INNER JOIN
table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId INNER JOIN
table_user AS u ON r.user_id = u.user_id INNER JOIN
table_labs AS l ON r.lab_id = l.lab_id INNER JOIN
table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY CAST(r.Shift as varchar(max), l.lab_title, u.user_name
You could also look at querying the data without the text column and then doing a second query to get the missing column. Example:
with temp as
(
SELECT l.lab_title AS [Assigned Lab], u.user_name AS [L/A], CONVERT(varchar(100), t.Time) + ' To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM table_roaster_time_table AS r INNER JOIN
table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId INNER JOIN
table_user AS u ON r.user_id = u.user_id INNER JOIN
table_labs AS l ON r.lab_id = l.lab_id INNER JOIN
table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY l.lab_title, u.user_name
)
SELECT r.Shift, t.lab_title AS [Assigned Lab], t.user_name AS [L/A] --etc
FROM table_roaster_time_table AS r
INNER JOIN temp as t
on r.id = t.id --or whatver
Also, this SQL seems unnecessary:
r.timeId = t.timeId AND r.timeId = t.timeId