如何忽略CTE Select语句中的重复记录?

时间:2018-03-15 15:15:12

标签: sql sql-server-2008 tsql

我试图忽略CTE中的重复记录,但我无法做到这一点,似乎CTE中的SELECT语句不允许使用ROWNUM()变量numrows来调整{{ 1}}子句,因为它在尝试时显示 WHERE 错误。

SQL查询:

Invalid column name 'numrows'

我还尝试在最后DECLARE @BatchID uniqueidentifier = NEWID(); DECLARE @ClusterID SMALLINT = 1; DECLARE @BatchSize integer = 20000; DECLARE @myTableVariable TABLE(EventID BIGINT,HotelID int, BatchStatus varchar(50),BatchID uniqueidentifier); WITH PendingExtResSvcEventsData_Batch AS( SELECT TOP (@BatchSize) t.EventID, t.HotelID, t.BatchStatus, t.BatchID, ROW_NUMBER() OVER (PARTITION BY t.EventID ORDER BY t.EventID) numrows FROM ExtResSvcPendingMsg t WITH (NOLOCK) WHERE t.ClusterID = @ClusterID AND numrows = 1 AND NOT EXISTS -- not allowed to use WHERE numrows = 1 here showing *Invalid Column Name* (select 1 from ExtResSvcPendingMsg t2 where t2.BatchStatus = 'Batched' and t2.EventID = t.EventID and t2.HotelID = t.HotelID) ) UPDATE PendingExtResSvcEventsData_Batch SET BatchStatus='Batched', BatchID = @BatchID -- WHERE numrows = 1 (not allowed to use WHERE here because of OUTPUT Clause) OUTPUT INSERTED.* INTO @myTableVariable SELECT e.ExtResSvcEventID,e.HotelID,e.ID1,e.ID2,e.ExtResSvcEventType,e.HostID,e.StatusCode,e.ChannelID,e.RequestAtTime,e.ProcessTime,e.DateBegin,e.DateEnd, e.StatusMsg,em.MsgBodyOut,em.MsgBodyIn,e.ChannelResID FROM ExtResSvcEvent e WITH (NOLOCK) INNER JOIN @myTableVariable t ON e.ExtResSvcEventID = t.EventID INNER JOIN ExtResSvcEventXML em with (nolock) on t.EventID = em.ExtResSvcEventID ORDER BY e.ExtResSvcEventID 中使用numrows,例如SELECT,但这会给我一个错误,即 INNER JOIN @myTableVariable t ON e.ExtResSvcEventID = t.EventID AND t.numrows = 1

如何在CTE中使用SELECT时忽略重复记录?

1 个答案:

答案 0 :(得分:0)

您不能引用CTE的WHERE子句中的numrows列,因为在计划执行的此时不计算该列。您需要使用select语句添加第二个CTE,您可以在其中引用numrows列:

WITH Base AS (
    SELECT TOP (@BatchSize) t.EventID, t.HotelID, t.BatchStatus, t.BatchID, ROW_NUMBER() OVER (PARTITION BY t.EventID ORDER BY t.EventID) numrows 
    FROM ExtResSvcPendingMsg t WITH (NOLOCK) 
    WHERE t.ClusterID = @ClusterID 
            AND NOT EXISTS  (select 1 from ExtResSvcPendingMsg t2 where t2.BatchStatus = 'Batched' and t2.EventID = t.EventID and t2.HotelID = t.HotelID)      
), PendingExtResSvcEventsData_Batch AS (
    SELECT  EventID,
            HotelID,
            BatchStatus,
            BatchID
    WHERE   numrows = 1
)
UPDATE...

我不能保证更新语句按预期工作,但PendingExtResSvcEventsData_Batch现在每个EventID应该有一行。