1

我正在尝试使以下 SQL 服务器语句工作,但我收到此错误:“无效的列名 'bfg'。”

WITH valDiff AS (
 SELECT 

  CASE 
   WHEN DATEADD(second, 604800, [InTime]) <= [OutTime] THEN [OutTime]
   ELSE DATEADD(second, 604800, [InTime]) 
  END AS bfg,

 datediff(second,
  CASE 
   WHEN [InTime] >= @in THEN [InTime]
   ELSE @in 
  END,
  CASE  
   WHEN bfg <= @out THEN bfg  
  ELSE @out 
 END) 

 AS v1 FROM [MyTable] 

 WHERE 
 AND [InTime] <= @out 
 AND  bfg >= @in

) SELECT SUM(v1) FROM valDiff;

简而言之,第一个带有 DATEADD 的 CASE 应该将 'bfg' 设置为 min(OutTime, InTime + 7 days)。第二部分或 DATEDIFF 应该计算 InTime 字段和上面计算的“bfg”之间的时间差(以秒为单位),如果它们在 @in 和 @out 时间范围内。

我希望我更了解 SQL ......你如何解决它?

4

1 回答 1

1

bfg在同一查询中创建别名后,您不能使用该别名。这样做的强烈需求通常意味着需要将代码放入 JOIN 子句中,以便您可以从别名中引用它。

INNER JOIN 解决方案

这是“漂亮”选项。再次加入你的桌子。

SELECT 
  T2.bfg,
  datediff(second,
    CASE WHEN [InTime] >= @in THEN [InTime] ELSE @in END,
    CASE WHEN T2.bfg <= @out THEN T2.bfg ELSE @out END) 
  AS v1 
FROM 
  [MyTable] as T1
  inner join
  ( SELECT MyTableID,
     CASE 
      WHEN DATEADD(second, 604800, [InTime]) <= [OutTime] THEN [OutTime]
      ELSE DATEADD(second, 604800, [InTime]) 
     END AS bfg
    FROM
     [MyTable]
  ) as T2 on T2.MyTableID = T1.MyTableID 
WHERE 
  [InTime] <= @out 
  AND  T2.bfg >= @in


查看方法

您可以创建一个视图,然后从中选择。

这样做一次:

CREATE VIEW MyView as
SELECT
 CASE 
   WHEN DATEADD(second, 604800, [InTime]) <= [OutTime] THEN [OutTime]
   ELSE DATEADD(second, 604800, [InTime]) 
  END AS bfg,
 *
FROM
 [MyTable]

然后,您的查询将如下所示:

WITH valDiff AS (
 SELECT 
  bfg,
  datediff(second,
   CASE 
    WHEN [InTime] >= @in THEN [InTime]
    ELSE @in 
   END,
   CASE  
    WHEN bfg <= @out THEN bfg  
   ELSE @out 
  END) AS v1 
FROM [MyView] 
WHERE 
 [InTime] <= @out 
 AND  bfg >= @in
) SELECT SUM(v1) FROM valDiff;


丑陋的解决方案

这只是将您的案例声明复制粘贴到 3 个位置的问题。

您必须bfg在 WHERE 子句(和其他位置)中替换为以下内容:

CASE 
 WHEN DATEADD(second, 604800, [InTime]) <= [OutTime] THEN [OutTime]
 ELSE DATEADD(second, 604800, [InTime]) 
END

这样您的整个代码将显示为:

WITH valDiff AS (
 SELECT 

  CASE 
   WHEN DATEADD(second, 604800, [InTime]) <= [OutTime] THEN [OutTime]
   ELSE DATEADD(second, 604800, [InTime]) 
  END AS bfg,

 datediff(second,
  CASE 
   WHEN [InTime] >= @in THEN [InTime]
   ELSE @in 
  END,
  CASE  
   WHEN 
     CASE WHEN DATEADD(second, 604800, [InTime]) <= [OutTime] THEN [OutTime]
     ELSE DATEADD(second, 604800, [InTime]) 
     END 
   <= @out THEN 
     CASE 
     WHEN DATEADD(second, 604800, [InTime]) <= [OutTime] THEN [OutTime]
     ELSE DATEADD(second, 604800, [InTime]) 
     END
  ELSE @out 
 END) 

 AS v1 FROM [MyTable] 

 WHERE 
 [InTime] <= @out 
 AND  CASE 
   WHEN DATEADD(second, 604800, [InTime]) <= [OutTime] THEN [OutTime]
   ELSE DATEADD(second, 604800, [InTime]) 
  END >= @in

) SELECT SUM(v1) FROM valDiff;
于 2011-07-16T04:28:21.833 回答