SQL从两个DateTime列获取最大日期和时间

时间:2015-02-04 03:05:17

标签: sql datetime max

我有一个我在黄鳍金枪鱼中挣扎的SQL查询(所以我不确定SQL版本)。

我想从表中获取最大修订版,但该表包含日期字段和时间字段(均为DateTime格式)。

到目前为止我写的是:

SELECT 
      a.MemberNo, 
      HealthScale, 
      status,
      a.EffDateTime = DATEADD(day, 0, DATEDIFF(day, 0, EffDate)) +
        DATEADD(day, 0 - DATEDIFF(day, 0, EffDate), EffTime)
FROM MembershipPlans AS a 
INNER JOIN
(
SELECT 
      MemberNo, 
      MAX(EffDateTime = DATEADD(day, 0, DATEDIFF(day, 0, EffDate)) +
        DATEADD(day, 0 - DATEDIFF(day, 0, EffDate), EffTime) 
FROM MembershipPlans GROUP BY MemberNo
) AS b
ON a.MemberNo = b.MemberNo AND a.EffDateTime = b.EffDateTime

我收到一条错误消息:

  

SQL语句无效。   从数据库返回的错误消息是:   ' ='附近的语法不正确。

我希望的结果是每个成员编号获得一行,显示最大效果和匹配的健康状况和状态。 非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

您的查询应该是这样的:

  SELECT a.MemberNo,HealthScale,status,a.EffDateTime, b.EffDateTime FROM
  (SELECT 
        MemberNo, 
        HealthScale, 
        status,
        DATEADD(day, 0, DATEDIFF(day, 0, EffDate)) +
        DATEADD(day, 0 - DATEDIFF(day, 0, EffDate), EffTime) AS EffDateTime
  FROM MembershipPlans) AS a 
  INNER JOIN
  (SELECT 
        MemberNo, 
        MAX(DATEADD(day, 0, DATEDIFF(day, 0, EffDate)) +
        DATEADD(day, 0 - DATEDIFF(day, 0, EffDate), EffTime)) AS EffDateTime 
   FROM MembershipPlans GROUP BY MemberNo) AS b
   ON a.MemberNo = b.MemberNo