在SELECT中使用DATEDIFF

时间:2014-07-17 17:28:27

标签: sql datediff

SELECT DISTINCT
    Test,
    FIRST_VALUE (CONVERT(DATE, datetime)) OVER (ORDER BY datetime DESC) StartDate,
    LAST_VALUE  (CONVERT(DATE, datetime)) OVER (ORDER BY datetime DESC) EndDate,
    DATEDIFF(MONTH, StartDate, EndDate)
FROM
    Tests

关于如何在SELECT中包含2个日期之间的区别的任何想法?

我希望能够使用值StartDate和EndDate但是我收到一条错误,说StartDate和EndDate是无效列。

2 个答案:

答案 0 :(得分:0)

您不能使用在同一SELECT子句中其他位置的SELECT子句中创建的别名,因此您需要放置FIRST_VALUE()LAST_VALUE()个函数在DATEDIFF()函数中:

SELECT DISTINCT
    Test,
    FIRST_VALUE (CONVERT(DATE, datetime)) OVER (ORDER BY datetime DESC) StartDate,
    LAST_VALUE  (CONVERT(DATE, datetime)) OVER (ORDER BY datetime DESC) EndDate,
    DATEDIFF(MONTH, FIRST_VALUE (CONVERT(DATE, datetime)) OVER (ORDER BY datetime DESC)
                  , LAST_VALUE  (CONVERT(DATE, datetime)) OVER (ORDER BY datetime DESC) )
FROM
    Tests

或者您可以在子查询/ cte:

中运行除DATEDIFF()之外的所有内容
SELECT *,DATEDIFF(MONTH, StartDate, EndDate)
FROM (SELECT DISTINCT
        Test,
        FIRST_VALUE (CONVERT(DATE, datetime)) OVER (ORDER BY datetime DESC) StartDate,
        LAST_VALUE  (CONVERT(DATE, datetime)) OVER (ORDER BY datetime DESC) EndDate
      FROM
        Tests
      ) AS sub

您也不能使用SELECT子句中WHERE子句中创建的别名,但您可以在ORDER BY中使用它们,当然也可以在任何外部查询中使用它们。< / p>

答案 1 :(得分:0)

作为备注,我认为您的查询等同于:

SELECT Test,
       CONVERT(DATE, MIN(datetime)) as StartDate,
       CONVERT(DATE, MAX(datetime) as EndDate,
       DATEDIFF(MONTH, CONVERT(DATE, MIN(datetime)), CONVERT(DATE, MAX(datetime)))
FROM Tests
GROUP BY Test;

函数MIN()MAX()更简洁。此外,查询更容易理解为group by而不是select distinct