再次陷入SQL语句。错误:“列名无效”

时间:2011-07-16 04:24:03

标签: sql sql-server case datediff dateadd

我正在尝试使以下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天)。第二部分或DATEDIFF应计算InTime字段和上面计算的'bfg'之间的时间差,如果它们落在@in和@out时间范围内。

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

1 个答案:

答案 0 :(得分: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个地点的问题。

您必须使用以下内容替换WHERE子句(和其他位置)中的bfg

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;