CTE中的最大语句数

时间:2019-04-08 22:14:20

标签: sql sql-server subquery

WITH abidAccount AS
(
    SELECT 
        [ID], AzureBlobInsertDate = MAX(AzureBlobInsertDate)
    FROM 
        [dba].[CurAccounts] 
    GROUP BY 
        ID
),
recentAccount AS
(
    SELECT ca.*
    FROM [dba].[CurAccounts] ca
    JOIN abidAccount aa ON aa.[id] = ca.[ID]
                        AND aa.azureblobInsertDate = ca.azureBlobInsertDate
),
abidDevice AS
(
    SELECT deviceID, azureBlobInsertDate = MAX(azureBlobInsertDate)
    FROM [dba].[CurrentDevices]
    GROUP BY DeviceID
),
recentDevice AS
(
    SELECT cd.*
    FROM [RZRExploreLayer3].[CurrentDevices] cd
    JOIN abidDevice ad ON ad.DeviceID = cd.DeviceID
                       AND ad.azureBlobInsertDate = cd.azureblobinsertdate
)
SELECT  
    rd.deviceId,
    rd.[DeviceReturned],
    rd.accountNumber,
    rd.[DeviceFormat],
    rd.[DeviceLabel],
    MAX(ra.azureBlobInsertDate) AS AzureBlobInsertDate
FROM            
    recentAccount ra
JOIN   
    recentDevice rd ON ra.[id] = rd.accountNumber
WHERE  
    rd.deviceReturned NOT LIKE 'Null'
GROUP BY   
    rd.deviceId, rd.[DeviceReturned], rd.accountNumber,
    rd.[DeviceFormat], rd.[DeviceLabel]
    /* deviceID, rd.[DeviceReturned], rd.accountNumber, ra.azureBlobInsertDate */
HAVING 
    COUNT(1) > 1 

如何将多个CTE合并到一个查询中?

我的查询试图确定是否有重复的记录,如果存在,则仅保留max(AzureBlobInsertDate)记录并删除其他重复项。然后合并CurAccounts和设备表中的所有结果。

非常感谢您提供的任何帮助。

0 个答案:

没有答案