I have this, and i get an error at set total. Why can\'t i access a cte many times?
ALTER PROCEDURE [dbo].[GetLeaguePlayers]
(
@idleague int,
@pageNu
Using CTE Multiple Times to collect Data
;with CTEReminder AS
(
Select r.ReminderID,r.IsVerificationRequired from ReminderTbl r -- main table
),
FileTaskCountTempTbl as
(
select COUNT(t.ReminderID) as FileTaskCount -- getting first result
from TaskTbl t
left join CTEReminder r on t.ReminderID = r.ReminderID
),
FollowUpCountTempTbl as
(
select COUNT(f.FollowUpID) as Total -- getting second result
from FollowUpTbl f --cte not used here
),
MachineryRegularTaskCountTempTbl as
(
select COUNT(t.ReminderID) as TotalCount -- getting third result
from TaskTbl t
left join CTEReminder r on t.ReminderID = r.ReminderID
),
FinalResultTempTbl as
(
select COUNT(t.ReminderID) as MachineryTaskCount, -- getting fourth result
(select * from MachineryRegularTaskCountTempTbl ) as MachineryRegularTaskCount, -- Combining earlier results to last query
(select * from FollowUpCountTempTbl ) as FollowUpCount, -- Combining earlier results to last query
(select * from FileTaskCountTempTbl ) as FileTaskCount -- Combining earlier results to last query
from TaskTbl t
left join CTEReminder r on t.ReminderID = r.ReminderID
)
select * from FinalResultTempTbl