将脚本转换为CTE

时间:2018-06-23 05:16:08

标签: sql-server common-table-expression

请,您能帮我这个疑问吗?

SELECT 
    [festno], 2 
FROM 
    dbo.V_sadad_isar 
WHERE 
    [festno] IN (SELECT DISTINCT [festno]
                 FROM 
                     (SELECT
                          [festno], ROW_NUMBER() OVER (PARTITION BY [festno] ORDER BY fisar DESC) AS rn
                      FROM
                          dbo.V_sadad_isar) T
                 GROUP BY festno
                 HAVING MAX(rn) = 1)  
    AND [darsad_janbaz] <> 50

1 个答案:

答案 0 :(得分:0)

尝试一下:

;with cte as (
    SELECT [festno], 
           ROW_NUMBER() OVER (PARTITION BY [festno] ORDER BY fisar DESC) AS rn
    FROM dbo.V_sadad_isar
), cte2 as (
    SELECT DISTINCT [festno]
    FROM cte
    GROUP BY festno
    HAVING MAX(rn) = 1
)

SELECT fastno, 2
FROM dbo.V_sadad_isar
WHERE festno IN (SELECT festno FROM cte2)

但是可以简化为:

;with cte as (
    SELECT DISTINCT [festno]
    FROM cte
    GROUP BY festno
    HAVING COUNT(*) = 1
)

SELECT fastno, 2
FROM dbo.V_sadad_isar
WHERE festno IN (SELECT festno FROM cte)