SQL Server:Max不使用time var

时间:2017-07-18 10:36:16

标签: sql sql-server time max

SELECT 
    *
FROM 
    SomeTable LV
WHERE 
    A IN ('0', '24', '25', '26', '27', '28')
    AND B <> 'ERRO'
    AND SAIDA <> 0 
    AND DATA IN (SELECT MAX(DATA) FROM SomeTable WHERE CB = LV.CB)
    AND HORA IN (SELECT MAX(Hora) FROM SomeTable WHERE CB = LV.CB 
                                                   AND DATA = LV.DATA)
    AND DATA >= CASE     
                   WHEN DATENAME(weekday, GetDate()) = 'Monday'  
                      THEN DATEADD(day, -3, CONVERT(DATE, GETDATE()))   
                   ELSE DATEADD(day, -2, CONVERT(DATE, GETDATE()))   
                END   
ORDER BY 
    DATA DESC, HORA DESC, B

有谁可以告诉我为什么max(hora)功能不起作用?它返回0值。

EXEC sp_help SomeTable

    Column_name Type    Computed    Length  Prec    Scale   Nullable    TrimTrailingBlanks  FixedLenNullInSource    Collation
    Data    date    no  3   10      0       no  (n/a)   (n/a)   NULL
    Hora    time    no  3   8       0       no  (n/a)   (n/a)   NULL

我想选择最长的日期和时间。

例如,对于容器,日期在这种情况下是相同的,但可能与其他日期不同。

NumLeitor   CB  Data    Hora    Saida   RepacDone   VerifDone   ReetiqDone

26  O7009419256 2017-07-17  23:02:57    1   0   0   0
25  O7009419256 2017-07-17  23:02:38    1   0   0   0
26  O7009419256 2017-07-17  22:52:14    1   0   0   0
25  O7009419256 2017-07-17  22:51:56    1   0   0   0

max(data)适用于具有不同日期的案例,但最大(hora) - 时间 - 不适用。

2 个答案:

答案 0 :(得分:0)

您需要合并“日期”和“时间”字段并对其进行评估。

select [MyDate]=CAST(DATA as DATETIME) + CAST(HORA as DATETIME)

现在使用它来检查'max'日期时间。喜欢的东西;

 SELECT 
    *
  FROM SomeTable LV
  WHERE A IN ('0','24','25','26','27','28')
  AND B <>'ERRO'AND SAIDA <>0
  and CAST(DATA as DATETIME) + CAST(HORA as DATETIME) in (SELECT MAX(CAST(DATA as DATETIME) + CAST(HORA as DATETIME)) FROM SomeTable WHERE CB=LV.CB)
  AND    DATA >=   
  CASE     WHEN DATENAME(weekday, GetDate())='Monday'  THEN  DATEADD(day, -3, convert(date, GETDATE()))   ELSE DATEADD(day, -2, convert(date, GETDATE()))   END   
  ORDER BY DATA DESC, HORA DESC,B

答案 1 :(得分:0)

select *
from (
    SELECT TOP 1 WITH TIES
        *
    FROM 
        SomeTable LV
    WHERE 
        A IN ('0', '24', '25', '26', '27', '28')
        AND B <> 'ERRO'
        AND SAIDA <> 0 
        AND DATA >= DATEADD(day, -3, CONVERT(DATE, GETDATE()))
    ORDER BY 
        DATA DESC, HORA DESC
) t
WHERE DATENAME(weekday, GetDate()) = 'Monday' 
    OR DATA >= DATEADD(day, -2, CONVERT(DATE, GETDATE()))   
order by B