如何在同一个选择中多次使用计算列而不重复表达式而不使用公用表表达式或复杂的子选择?
DECLARE @T TABLE ( NUM1 INT,NUM2 INT)
INSERT INTO @T VALUES (2,3);
INSERT INTO @T VALUES (5,7);
INSERT INTO @T VALUES(32,3);
INSERT INTO @T VALUES(6,8);
SELECT (NUM1+NUM2) [ADD], [ADD]*2, [ADD]/2,* FROM @T
有没有办法在SQL Server 2005中解决这个问题?
答案 0 :(得分:12)
您可以使用交叉申请
SELECT T2.[ADD],
T2.[ADD]*2,
T2.[ADD]/2
FROM @T AS T1
CROSS APPLY (SELECT T1.NUM1+T1.NUM2) AS T2([ADD])
或CTE
WITH C AS
(
SELECT NUM1+NUM2 AS [ADD]
FROM @T
)
SELECT [ADD],
[ADD]*2,
[ADD]/2
FROM C
或子查询(也称为派生表)
SELECT T.[ADD],
T.[ADD]*2,
T.[ADD]/2
FROM (
SELECT NUM1+NUM2 AS [ADD]
FROM @T
) AS T
无法在声明的相同字段列表中使用列别名。
答案 1 :(得分:1)
您可以使用派生表来完成此任务:
SELECT
*,
[ADD]*2,
[ADD]/2
FROM
(
SELECT (NUM1+NUM2) AS [ADD], NUM1, NUM2 FROM @T
) AS A