我使用以下查询来尝试通过减去两列之间的值来获取日期差异。以下是此查询的一部分:
SELECT
ISNULL(MIN(c.CreatedOn), 0) AS [StartDate],
ISNULL(MIN(s.CreatedOn), 0) AS [EndDate],
Duration = [EndDate]-[StartDate]
FROM MyTable
INNER JOIN...
我收到的错误表明我的列名无效。 是否有可能以这种方式编写查询?
答案 0 :(得分:1)
以前定义的列别名不能在同一查询中使用。改为使用实际计算。
SELECT
ISNULL(MIN(c.CreatedOn), 0) AS [StartDate],
ISNULL(MIN(s.CreatedOn), 0) AS [EndDate],
Duration = ISNULL(MIN(s.CreatedOn), 0)-ISNULL(MIN(c.CreatedOn), 0)
FROM MyTable
INNER JOIN...
答案 1 :(得分:1)
您不能在同一查询中使用别名。如果必须使用它们,则可以使用嵌套查询或WITH
语句。
嵌套查询
Select StartDate, EndDate,
Duration = [EndDate]-[StartDate]
From
(
SELECT
ISNULL(MIN(c.CreatedOn), 0) AS [StartDate],
ISNULL(MIN(s.CreatedOn), 0) AS [EndDate]
FROM MyTable
INNER JOIN...
) InnerQuery
WITH声明
;With InnerQuery AS
(
SELECT
ISNULL(MIN(c.CreatedOn), 0) AS [StartDate],
ISNULL(MIN(s.CreatedOn), 0) AS [EndDate]
FROM MyTable
INNER JOIN...
)
Select StartDate, EndDate,
Duration = [EndDate]-[StartDate]
From InnerQuery
答案 2 :(得分:0)
select datediff(day, min('12/01/2014'), min(getdate()))
P.S。,当您将日期数据类型添加到int时,您还期待什么?
select isnull(cast(null as date), 0)