在SELECT语句SQL中的其他聚合函数中使用聚合函数

时间:2014-07-29 15:12:42

标签: sql sql-server

我有这个非常大的聚合函数,我必须在另一列中使用两次,有没有办法写下来而不必写出第一个函数三次? 所以我想要这样的事情:

Select
volumet =
CASE When sum(volume)>200, then 200
     Else sum(volume)
END,
sum(volumet * price) / volumet - price2 * volumet as Profit
FROM tablex

2 个答案:

答案 0 :(得分:1)

Select
sum(volumet * price) / volumet - price2 * volumet as Profit
FROM
(Select
CASE When sum(volume)>200, then 200
     Else sum(volume)
END as volumet, price, price2
FROM tablex) as tableAux

答案 1 :(得分:0)

根据您的原始帖子,这样的内容应该是您正在寻找的内容。

WITH CTE 
AS
(
    SELECT
        sum(volumet) AS volumet
    ,   price
    ,   price2
    FROM tablex
    group by price, price2
)
, VolumetValues as
(
    select case when volumet > 200 then 200 else volumet end as volumet
        , price
        , price2
    from CTE
)

SELECT 
    (volumet * price) / volumet - price2 * volumet as Profit
FROM VolumetValues