简体   繁体   English

根据表格中的计算值获取最小值和最大值

[英]Getting Min and Max based on calculated values in a table

I am selecting some rows from a temporary table, #t1, that I have created: 我正在从我创建的临时表#t1中选择一些行:

SELECT FutContract, 
    Quantity, 
    Date, 
    Price, 
    TotalQuantity,
    PercentOfTotalQ, 
    CumulativePercentile=
        (SELECT ROUND(SUM(PercentOfTotalVol),2) FROM #t1 b
        WHERE b.OvernightVol <= a.OvernightVol AND b.FutContract = a.FutContract)

FROM #t1 a

I would like to create two more rows that represent the MIN(Price) and MAX(Price) for which CumulativePercentile is greater than 0.3 (30th percentile), but the only ways that I can think of doing it involve creating another temporary table. 我想创建另外两行代表MIN(Price)和MAX(Price),其中CumulativePercentile大于0.3(第30百分位数),但我能想到的唯一方法是创建另一个临时表。 I would prefer not to have to, if possible. 如果可能的话,我宁愿不要这样做。 Any ideas? 有任何想法吗?

EDIT: 编辑:

;WITH z AS
(SELECT FutContract, OvernightVol, MorningDate, Price, TotalVol,
    PercentOfTotalVol, CumulativePercentile=
    (SELECT ROUND(SUM(PercentOfTotalVol),2) FROM #t1 b
    WHERE b.OvernightVol <= a.OvernightVol AND b.FutContract = a.FutContract) FROM #t1 a)

    SELECT *, 
        (SELECT MIN(Price) OVER(PARTITION BY FutContract) FROM z WHERE CumulativePercentile > 0.3) AS min70px,
        (SELECT MAX(Price) OVER(PARTITION BY FutContract) FROM z WHERE CumulativePercentile > 0.3) AS max70px
FROM z

if you are on SQL Server 2005 or higher, a CTE should help 如果您使用的是SQL Server 2005或更高版本,则CTE应该会有所帮助

;with z as 
(SELECT FutContract, 
    Quantity, 
    Date, 
    Price, 
    TotalQuantity,
    PercentOfTotalQ, 
    CumulativePercentile=
        (SELECT ROUND(SUM(PercentOfTotalVol),2) FROM #t1 b
        WHERE b.OvernightVol <= a.OvernightVol AND b.FutContract = a.FutContract)

FROM #t1 a
)
select 
(select min(price) from z Z1 where Z1.CumulativePercentile > 0.3 and Z1.FutContract = z.FutContract) min_price,
(select max(price) from z Z1 where Z1.CumulativePercentile > 0.3 and Z1.FutContract = z.FutContract) max_price,
*
from z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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