复制SQL语句的语法是什么?

时间:2015-07-16 18:42:52

标签: sql ms-access

我是SQL的新手,我想看看是否有人可以帮助我复制基本SQL百分位语句的语法。这是我想要复制的代码:

SELECT Max(CompData.Salary) AS 50th
FROM (SELECT TOP 50 PERCENT Salary FROM CompData ORDER BY Salary)  AS [%$##@_Alias];

我试过这个:

SELECT Max(CompData.Salary) AS 50th
FROM (SELECT TOP 50 PERCENT Salary FROM CompData ORDER BY Salary)  AS [%$##@_Alias],
FROM (SELECT TOP 60 PERCENT Salary FROM CompData ORDER BY Salary)  AS [%$##@_Alias];

我得到了Syntax错误FROM子句 例如,如何为第60百分位复制此(没有语法错误)?

非常感谢!

1 个答案:

答案 0 :(得分:2)

您的问题是第二个from。 SQL SELECT只有一个FROM子句(其他from子句将在子查询中。)

想要做你正在尝试的事情。问题是,做笛卡尔积。因此,如果您的表有1,000行,那么您的中间结果将具有500 * 600 = 300,000行 - 并且性能受到很大影响。

您可以使用percentile_disc()precentile_cont()来实现此目的。但是,对于您的查询,您只想在加入之前进行聚合

SELECT q50.val, q60.val
FROM (SELECT Max(CompData.Salary) AS val
      FROM (SELECT TOP 50 PERCENT Salary FROM CompData ORDER BY Salary) t
     ) q50 CROSS JOIN
     (SELECT Max(CompData.Salary) AS val
      FROM (SELECT TOP 50 PERCENT Salary FROM CompData ORDER BY Salary) t
     ) q60;

还有其他方法可以进行此计算,但这似乎就是您在问题中使用的方法。

编辑:

您的问题被标记为 SQL SERVER 而不是 MS ACCESS 。标签很重要。 MS Access语法更像是:

SELECT q50.val, q60.val
FROM (SELECT Max(CompData.Salary) AS val
      FROM (SELECT TOP 50 PERCENT Salary FROM CompData ORDER BY Salary) as t
     ) as q50,
     (SELECT Max(CompData.Salary) AS val
      FROM (SELECT TOP 50 PERCENT Salary FROM CompData ORDER BY Salary) as t
     ) as q60;