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;