用 Union 语句中的值计算

Calculate with Values in Union Statement

在 SQL 服务器中,我正在寻找在联合 select 中重用值以在计算中使用它们的最佳方法:

喜欢:

---------------------
select max(value) as V1
from table

union

select min(value) as V2
from table

union

select V1 + V2 as V3
from table

我知道的唯一方法是像这样声明:

---------------------
declare @V1 as int
declare @V2 as int

select
@V1 = max(value)
@V2 = min(value)
from table

select @V1
union
select @V2
union
select @V1 + @V2

这可行,但没有更简单的方法吗?

在 SQL 服务器中,我建议 cross apply 将列转为行:

select x.v
from (select min(value) v1, max(value) v2 from mytable) t
cross apply (values (t.v1), (t.v2), (t.v1 + t.v2)) x(v)

使用 returns 最小值和最大值的 CTE:

with cte as (select min(value) min_value, max(value) max_value from tablename)
select min_value from cte
union
select max_value from cte
union
select min_value + max_value from cte

你可以使用 STRING_SPLIT 因为它比 pivot

declare @a as varchar
select @a=cast(min(value) as varchar)+','+cast(min(value)+max(value) as varchar)+','+cast(max(value) as varchar) 
from tablename

SELECT value
FROM STRING_SPLIT(@a, ',' )