Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

seleziona top N dinamicamente con N dalla stessa istruzione select

Puoi usare row_number() fare essenzialmente la stessa cosa:

WITH DataToInsert AS
(
    Select AgentID, Surveys, LOB,(case when day(getdate())<4 then 3 else (day(getdate())) - (Surveys*3) end) SampleSize from Current_Agent_SurveyCount_HSI Where surveys<8 
)
Insert Into Survey_Source_New (LOB, CenterName, CallDate, AgentZid, TN, Ticket, RecordingID, Cycle, [TimeStamp])  
    select LOB, CenterName, CallDate, AgentZid, TN, Ticket, RecordingID, Cycle, [TimeStamp]
    from (Select ss.LOB, CenterName, CallDate, AgentZid, TN, Ticket, RecordingID, Cycle, [TimeStamp],
                 row_number() over (order by newid()) as seqnum
          From Survey_source_Level1 ss inner join
               DataToInsert du on ss.AgentZID=du.agentID
          where flag is null and du.samplesize<7
         ) t
    where seqnum <= du.sample_size

Potresti essere in grado di semplificarlo un po', ma non so se flag proviene da du o ss.