开发者

Functions, variables and nested selects

Say you have a nested SQL in SQL Server in which you need to use the result of a function evaluated on the outer select:

开发者_如何转开发
SELECT FUN(...) as Result,
       (SELECT count(*)
        FROM Table
        WHERE ... < Result
FROM Table
WHERE Condition

That won't work because of an 'unknown column Result' in the inner query.

How can I rewrite it?


How about nesting things differently:

SELECT
  r.Result,
  (SELECT COUNT(*) FROM Table WHERE ... < r.Result) AS SomeCount
FROM
  (
    SELECT FUN(...) AS Result, ... FROM Table WHERE Condition
  ) AS r


I'd consider something like this instead if you're on SQL Server 2005

SELECT
  ...
FROM
  (
  SELECT FUN(...) AS Result, ... FROM Table WHERE Condition
  ) foo
  CROSS APPLY
  (
  SELECT COUNT(*) AS SomeCount FROM Table WHERE ... < foo.Result
  )

Note: the query you posted can often be solved using window/ranking functions in SQL Server 2005+

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜