1

我有一条 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

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

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
4

3 回答 3

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

这与您要求的结果不一致,但我认为这些是错误的,我认为您应该检查它们。

于 2012-08-10T12:04:31.987 回答
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
于 2012-08-10T15:54:06.993 回答
-2

添加订单 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
于 2012-08-10T12:05:33.860 回答