在SQL中返回各种百分位数

时间:2015-02-20 14:04:41

标签: sql ms-access ms-access-2010

我有一段代码返回一组数据的第90个百分位数,我正在尝试更改代码以返回其他百分位数(25th,50th,75th)。以下是成功返回第90个百分位数(无插值)的代码:

SELECT Max ([Subquery]![RECP]) AS RECP90P
FROM (SELECT TOP 90 PERCENT [RECP] FROM [CompData Query] ORDER BY [RECP] DESC)  AS Subquery;

我的想法是,如果我将代码更改为以下代码,我将能够返回第25个百分位数。以下是我的尝试:

SELECT Min ([Subquery]![RECP]) AS RECP25P
FROM (SELECT TOP 75 PERCENT [RECP] FROM [CompData Query] ORDER BY [RECP] DESC)  AS Subquery;

我知道SQL中没有SELECT BOTTOM所以我试图使用MIN来返回反转。但是,当我尝试运行此代码时,我返回一个空值。我尝试将DESC更改为ASC,以为MIN可能会返回第一个值,而不是所有值的最小值,但是即使这返回了一个空白值。有人能够解释我哪里出错吗?

这样的工作会改变吗?

SELECT Max([CompData Query]![AgedSalary]) CASE ([CompData Query]![Code]) WHEN "RECP" AS RECP90P
FROM (SELECT TOP 90 PERCENT [AgedSalary] FROM [CompData Query] ORDER BY [RECP] DESC)  AS Subquery;

您是否能够解释为什么CASE WHEN错误和/或错过了“运营商”:

SELECT CASE ([CompData Query]![Code]) WHEN "RECP" THEN SELECT Max([CompData Query]![AgedSalary]) AS RECP90P FROM (SELECT TOP 90 PERCENT [AgedSalary] FROM [CompData Query] ORDER BY [AgedSalary] DESC) ELSE 'Unknown' END;

谢谢。

1 个答案:

答案 0 :(得分:1)

我认为Access有一个TRIM()函数,但LTRIM,RTRIM和TRIM中的任何一个都应该做你想要的。

SELECT Min ([Subquery]![RECP]) AS RECP25P
FROM (
    SELECT TOP 75 PERCENT [RECP]
    FROM [CompData Query]
    WHERE RTRIM([RECP]) <> ''
    ORDER BY [RECP] DESC
)  AS Subquery;