使用SQL选择具有最近日期的行

时间:2012-08-10 11:55:28

标签: sql-server date exists

我有一个SQL语句。

SELECT 
    ID, LOCATION, CODE,MAX(DATE),FLAG 
FROM 
    TABLE1 
WHERE 
     DATE <= CONVERT(DATETIME,'11-11-2012') 
     AND EXISTS (SELECT * FROM #TEMP_CODE WHERE TABLE1.CODE = #TEMP_CODE.CODE) 
     AND ID IN (14, 279)
GROUP BY 
     ID, LOCATION, CODE

我需要与11-11-2012最近的日期的行,但该表返回所有值。我究竟做错了什么。谢谢

ID     LOCATION              CODE            DATE              FLAG
-------------------------------------------------------------------
14  CAR STREET,UDUPI         234      2012-08-08 00:00:00.000   0
14  CAR STREET,UDUPI         234      2012-08-10 00:00:00.000   1
14  CAR STREET,UDUPI         234      2012-08-14 00:00:00.000   0
279 MADHUGIRI                234      2012-08-08 00:00:00.000   1
279 MADHUGIRI                234      2012-08-11 00:00:00.000   0

我想只显示日期小于或等于给定日期的行。所需的结果是

ID     LOCATION              CODE            DATE              FLAG
-------------------------------------------------------------------
14  CAR STREET,UDUPI         234      2012-08-10 00:00:00.000   1
279 MADHUGIRI                234      2012-08-11 00:00:00.000   0

3 个答案:

答案 0 :(得分:3)

;WITH x AS 
(
  SELECT ID, Location, Code, Date, Flag, 
    rn = ROW_NUMBER() OVER 
    (PARTITION BY ID, Location, Code ORDER BY [Date] DESC)
  FROM dbo.TABLE1 AS t1
  WHERE [Date] <= '20121111'
  AND ID IN (14, 279) -- sorry, missed this
  AND EXISTS (SELECT 1 FROM #TEMP_CODE WHERE CODE = t1.CODE)
)
SELECT ID, Location, Code, Date, Flag
FROM x WHERE rn = 1;

这会产生:

ID  LOCATION         CODE [Date]     FLAG
--- ---------------- ---- ---------- ----
14  CAR STREET,UDUPI 234  2012-08-14 0
279 MADHUGIRI        234  2012-08-11 0

这不符合您的要求,但我认为这些错误,我认为您应该检查它们。

答案 1 :(得分:2)

使用子查询获取每个ID的最大日期,然后将其加入到您的表中:

SELECT 
    ID, LOCATION, CODE, DATE, FLAG 
FROM 
    TABLE1 
JOIN (
    SELECT ID AS SubID, MAX(DATE) AS SubDATE 
    FROM TABLE1 
    WHERE DATE < '11/11/2012'
        AND EXISTS (SELECT * FROM #TEMP_CODE WHERE TABLE1.CODE = #TEMP_CODE.CODE) 
        AND ID IN (14, 279)
    GROUP BY ID
    ) AS SUB ON ID = SubID AND DATE = SubDATE

答案 2 :(得分:-2)

添加Order BY DATE LIMIT 0,2

根据您的订单,您将按最接近您的条件的日期顺序在哪里和限制将仅返回前2个值!

SET ROWCOUNT 2  
SELECT 
    ID, LOCATION, CODE,MAX(DATE),FLAG 
FROM 
    TABLE1 
WHERE 
     DATE <= CONVERT(DATETIME,'11-11-2012') 
     AND EXISTS (SELECT * FROM #TEMP_CODE WHERE TABLE1.CODE = #TEMP_CODE.CODE) 
     AND ID IN (14, 279)
GROUP BY 
     ID, LOCATION, CODE
ORDER BY DATE