简体   繁体   中英

using aggregate function in other aggregate function in the SELECT statement SQL

I am having this pretty big aggregate function that I have to use twice in another column, is there a way to write this down without having to write out the first function three times? So I would like something like this:

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

Something like this should be what you are looking for based on your original post.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM