多个查询作为单个查询

时间:2014-04-23 06:27:22

标签: sql postgresql

两个查询

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  deodar

执行操作后,我想显示结果

2 个答案:

答案 0 :(得分:1)

简单的答案是您可以使用子选择。

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

目前尚不清楚是否要在过滤之前或之后应用LEAD操作。如果您希望在过滤之前应用它们,则可以颠倒嵌套的顺序。

对于更复杂的操作,或者为了更好的可读性/可维护性,PostgreSQL(和最近的ANSI SQL)支持Common Table Expressions,允许您创建多个虚拟表并从中进行选择。各种虚拟表可以相互引用 - 甚至是递归的。 Microsoft has some pretty good documentation.

根据您使用的SQL引擎,CTE可能与子选择的执行方式不同。在虚拟表仅使用一次的简单情况下,子选择可能表现更好(如果存在任何性能差异)。

CTE解决方案看起来像这样:

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

答案 1 :(得分:0)

SELECT wavelength,reflectance 
FROM
    (SELECT ROW_NUMBER() OVER(ORDER BY NULL) As RowNumber,* FROM deodar) As foo         
WHERE(RowNumber%5=0)

UNION

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

使用UNION的唯一条件是所有查询都必须返回相同的列(类型和名称)。