多个查询执行为公式派生

时间:2014-04-23 07:29:47

标签: sql postgresql

第一次查询

WITH bar AS (
       SELECT wavelength, reflectance 
       FROM
         (SELECT 
             ROW_NUMBER() OVER(ORDER BY NULL) As RowNumber, * 
          FROM deodar) As foo 
       WHERE (RowNumber % 5 = 0)
     )
    SELECT
       wavelength, 
       (LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength) /
         (CASE WHEN (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) = 0 THEN 1
               ELSE (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) END)
          AS reflectance   
    FROM bar 

此查询输出作为下一个操作的输入,再次从上述查询的输入执行此公式以显示结果。

第二次查询

 SELECT
          wavelength, 
          (LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength) /
            (CASE WHEN (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) = 0 THEN 1
                  ELSE (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) END)
             AS reflectance

第一次执行查询后,它会将其输出作为第二次查询的输入并再次执行操作..

查询

SELECT 
   wavelength, 
   (LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength) /
     (CASE WHEN (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) = 0 THEN 1
           ELSE (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) END)
      AS reflectance 
FROM (SELECT 
   wavelength, 
   (LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength) /
     (CASE WHEN (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) = 0 THEN 1
           ELSE (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) END)
      AS reflectance   
FROM (
   SELECT wavelength, reflectance 
   FROM
     (SELECT 
         ROW_NUMBER() OVER(ORDER BY NULL) As RowNumber, * 
      FROM deodar) As foo 
   WHERE (RowNumber % 5 = 0)
) )bar

此查询提供错误...

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

SELECT 
   wavelength, 
   (LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength) /
     (CASE WHEN (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) = 0 THEN 1
           ELSE (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) END)
      AS reflectance 
FROM (SELECT 
   wavelength, 
   (LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength) /
     (CASE WHEN (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) = 0 THEN 1
           ELSE (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) END)
      AS reflectance   
FROM (
   SELECT wavelength, reflectance 
   FROM
     (SELECT 
         ROW_NUMBER() OVER(ORDER BY NULL) As RowNumber, * 
      FROM deodar) As foo 
   WHERE (RowNumber % 5 = 0)
)results )bar --alias added here

从子查询中选择时,子查询必须具有别名(=名称):典型语法为SELECT foo FROM (subquery) name(强调名称)。您可以将AS name代替name,但这不是强制性的。

在这种情况下,使用带括号匹配的编辑器非常有用。