Use one CTE many times

后端 未结 6 1969
鱼传尺愫
鱼传尺愫 2020-12-13 17:16

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         


        
6条回答
  •  萌比男神i
    2020-12-13 17:25

    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 
    

提交回复
热议问题