SQL在列上创建变量

SQL在列上创建变量,sql,sql-server,Sql,Sql Server,我有一个查询,它随着相同列的求和而变得重复。我想做的是创建一个变量,这样我的代码就不会变得不必要的混乱。 一个简单的例子: SELECT (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)/2 AS half, (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)/3 AS third, (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)/4 AS fourt

我有一个查询,它随着相同列的求和而变得重复。我想做的是创建一个变量,这样我的代码就不会变得不必要的混乱。 一个简单的例子:

SELECT 
    (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)/2 AS half,
    (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)/3 AS third,
    (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)/4 AS fourth,
    (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)*2 AS twice,
    b.sepCol
FROM [Table A] a
JOIN [Table B] b ON b.someCol = a.someCol
我希望能够消除将总和(col1…col5)键入以下内容的需要:

@myVar = (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)
SELECT 
    @myVar/2 AS half,
    @myVar/3 AS third,
    @myVar/4 AS fourth,
    @myVar*2 AS twice,
    b.sepCol
FROM [Table A] a
JOIN [Table B] b ON b.someCol = a.someCol

最好是将其保留在同一个查询中,如果可能的话,不必使用CTE或TENTABLE。

我将使用
应用

SELECT aa.cols/2 AS half,
       aa.cols/3 AS third,
       aa.cols/4 AS fourth,
       aa.cols*2 AS twice,
       b.sepCol
FROM [Table A] a INNER JOIN
     [Table B] b
     ON b.someCol = a.someCol CROSS APPLY
     ( VALUES (a.col1 + a.col2 + a.col3 + a.col4 + a.col5) 
     ) aa (cols);

我会使用
APPLY

SELECT aa.cols/2 AS half,
       aa.cols/3 AS third,
       aa.cols/4 AS fourth,
       aa.cols*2 AS twice,
       b.sepCol
FROM [Table A] a INNER JOIN
     [Table B] b
     ON b.someCol = a.someCol CROSS APPLY
     ( VALUES (a.col1 + a.col2 + a.col3 + a.col4 + a.col5) 
     ) aa (cols);

您可以将其用作内部查询,如

SELECT 
    myVar/2 AS half,
    myVar/3 AS third,
    myVar/4 AS fourth,
    myVar*2 AS twice
FROM (
SELECT (col1 + col2 + col3 + col4 + col5) as myvar, b.sepCol
FROM TableA ) xxx

您可以将其用作内部查询,如

SELECT 
    myVar/2 AS half,
    myVar/3 AS third,
    myVar/4 AS fourth,
    myVar*2 AS twice
FROM (
SELECT (col1 + col2 + col3 + col4 + col5) as myvar, b.sepCol
FROM TableA ) xxx
我想你错过了这里的b.sepCol专栏我想你错过了这里的b.sepCol专栏你也错过了b.sepCol专栏:)你也错过了b.sepCol专栏:)