SQL Server 仅获取表的子集的最新日期,要更好地构建SQL查询,请避免使用CTE

jk9hmnmh  于 2022-11-21  发布在  其他
关注(0)|答案(2)|浏览(129)

如何以更好的方式编写这个SQL查询。我可以避免使用CTE吗?
对于table_1的子集,我只需要获取integration_date最新的数据。对于不在子集中的数据(variable_A!= 'X'),我需要table_1中的所有数据。

Latest_dates AS ( SELECT MAX(INTEGRATION_DATE) AS MAX_INTEGRATION_DATE, ID FROM table_1 GROUP BY ID) 
    SELECT S.* FROM Table_1 AS S 
                LEFT JOIN Latest_dates ON S.INTEGRATION_DATE = Latest_dates.MAX_INTEGRATION_DATE AND S.ID= Latest_dates.ID 
                WHERE Latest_dates.MAX_INTEGRATION_DATE is not NULL 
                OR S.variable_A != 'X'

代码工作正常,但看起来很难看。

yyhrrdl8

yyhrrdl81#

您不需要避免使用CTE,但可以使用ranking functions

WITH CTE AS
(
    SELECT ID, INTEGRATION_DATE, 
           IdDateRank = RANK() OVER (PARTITION BY ID ORDER BY INTEGRATION_DATE DESC)
          -- other columns
    WHERE S.variable_A != 'X'
)
SELECT ID, INTEGRATION_DATE -- other columns
FROM CTE WHERE IdDateRank = 1
ev7lccsx

ev7lccsx2#

select top 1 * with ties 
from Table_1 
order by row_number() over (partition by id order by case when variable_A = 'X' then null else INTEGRATION_DATE end desc) asc

相关问题