尝试检索2个日期时SQL混淆

时间:2016-11-04 18:47:08

标签: sql-server

我想查询一个表并在2个分隔行上设置日期,第一行是最接近今天的日期,最后一行包含最大日期。

我想出了这个:

SELECT           
    ID_CAND, DATE_JOUR
FROM         
    Paie.dbo.PAI_CAND_JOUR_NON_DISPO nd
WHERE        
    (ID_CAND = 16246)  
    AND (DATE_JOUR = (SELECT MIN(DATE_JOUR) AS Expr1
                      FROM Paie.dbo.PAI_CAND_JOUR_NON_DISPO AS ds
                      WHERE (ds.ID_CAND = nd.ID_CAND) 
                        AND (DATE_JOUR > GETDATE())) 
         OR
         DATE_JOUR = (SELECT MAX(DATE_JOUR) AS Expr1
                      FROM Paie.dbo.PAI_CAND_JOUR_NON_DISPO AS ds
                      WHERE (nd.ID_CAND = ds.ID_CAND) 
                        AND (DATE_JOUR > GETDATE())))

它只返回一行......但是当我分别运行内部选择时:

SELECT       
    MIN(DATE_JOUR) AS Expr1
FROM            
    Paie.dbo.PAI_CAND_JOUR_NON_DISPO AS ds
WHERE        
    (ID_CAND = 16246) AND (DATE_JOUR > GETDATE())

SELECT        
    MAX(DATE_JOUR) AS Expr1
FROM
    Paie.dbo.PAI_CAND_JOUR_NON_DISPO AS ds
WHERE        
    (ID_CAND = 16246) AND (DATE_JOUR > GETDATE()) 

确实会返回2个不同的值...我做错了什么?

1 个答案:

答案 0 :(得分:2)

也许这可以帮助

Select MinDate = min(case when DATE_JOUR >= GETDATE() then DATE_JOUR else null end)
      ,MaxDate = max(DATE_JOUR)
 From  Paie.dbo.PAI_CAND_JOUR_NON_DISPO          
 Where ID_CAND = 16246

对于两个单独的行

Select Expr1 = min(case when DATE_JOUR >= GETDATE() then DATE_JOUR else null end)
 From  Paie.dbo.PAI_CAND_JOUR_NON_DISPO          
 Where ID_CAND = 16246
Union  All
Select Expr1 = max(DATE_JOUR)
 From  Paie.dbo.PAI_CAND_JOUR_NON_DISPO          
 Where ID_CAND = 16246