我设置了一个像SUM(someColumn) AS [ColumnName]
这样的列名后,我怎么能在之后使用它呢?
假设我构建了一个这样的查询:
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
-- I need [TotalFooBar]
在同一个选项中我想要[TotalFoo]
和[TotalBar]
的总和。有可能参考这些专栏吗?我可以做很多事情:
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
SUM((foo.A + foo.B + foo.C + foo.D + foo.E) +
(bar.A + bar.B + bar.C + bar.D + bar.E)) AS [TotalFooBar]
这个例子没问题,但我有方式更多列,很难遵循。如果我必须使用这个列([TotalFooBar])怎么办?我每次都要重写整个SUM吗? 我正在寻找的是这样的:
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
SUM([TotalFoo] + [TotalBar]) AS [TotalFooBar]
甚至可能吗?
答案 0 :(得分:5)
否,您无法在同一SELECT
语句中执行此操作,但您可以使用子查询:
SELECT
TotalFoo,
TotalBar,
TotalFoo + TotalBar AS TotalFooBar
FROM
(
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
...
FROM ...
) AS sub
...
或CTE:
WITH CTE
AS
(
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
...
FROM ...
)
SELECT
TotalFoo,
TotalBar,
TotalFoo + TotalBar AS TotalFooBar
FROM CTE