加入子查询并提取最新日期

时间:2018-09-20 14:57:00

标签: sql sql-server tsql date

我有两个表:

客户

ID   NAME
001  John
002  Sara

CLIENT_STATUS

CLIENT_ID   STATUS   DATE
001         3        2018-01-02
001         2        2018-01-04
002         2        2018-01-02
002         1        2018-01-03

我想按status = 1进行过滤,我只想要指定时间范围内的最新日期。

到目前为止,我已经拥有了:

DECLARE 
    @StartDate  DATE,
    @EndDate    DATE
SET @StartDate  = '2016-07-01'    
SET @EndDate    = '2018-06-30'    

SELECT 
   c.NAME
 , c.ID
 , cs.STATUS
FROM CLIENT c
LEFT JOIN (
    SELECT cs.CLIENT_ID, cs.DATE 
    FROM CLIENT_STATUS 
    WHERE STATUS = 1 AND h.DATE BETWEEN @StartDate AND @EndDate
) AS hst ON hst.CLIENT_ID = c.ID

仅在最近日期之前不订购。

请注意,这是较大查询的一部分。

2 个答案:

答案 0 :(得分:2)

左(或INNER)与具有行号的子查询联接:

SELECT *
FROM CLIENTS
LEFT JOIN (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY CLIENT_ID ORDER BY DATE DESC) AS rn
    FROM CLIENT_STATUS
    WHERE STATUS = 1
) RECENT_STATUS ON CLIENTS.ID = RECENT_STATUS.CLIENT_ID AND RECENT_STATUS.rn = 1

答案 1 :(得分:1)

您可以使用row_number()函数:

SELECT TOP (1) WITH TIES c.ID, c.NAME, cs.DATE
FROM CLIENT c INNER JOIN
     CLIENT_STATUS cs
     ON cs.CLIENT_ID = c.ID 
WHERE cs.STATUS = 1 AND cs.DATE >= @StartDate AND cs.DATE <= @EndDate
ORDER BY ROW_NUMBER() OVER (PARTITION BY c.ID ORDER BY cs.DATE DESC);