2011-01-13 263 views
0

我有兩個查詢返回雙精度值的單柱:司在SQL查詢語句

(SELECT scale 
    FROM (SELECT title, 
       scale, 
       dense_rank() OVER (PARTITION BY title 
             ORDER BY scale ASC) AS r 
      FROM signatures) t 
    WHERE r = 1) 

...和:

(SELECT scale 
    FROM (SELECT scale, 
       dense_rank() OVER (PARTITION BY title 
             ORDER BY scale ASC) AS r 
      FROM signatures) t 
    WHERE r = 2) 

我想選擇第一個查詢( Q1)除以第二個查詢(Q2)。即,(Q1的第1行)/(Q2的第1行)。並繼續沿着其餘的行。

我曾嘗試:

SELECT ((SELECT scale 
      FROM (SELECT title, 
         scale, 
         dense_rank() OVER (PARTITION BY title 
               ORDER BY scale ASC) AS r 
        FROM signatures) t 
      WHERE r = 1) 

/

(SELECT scale 
    FROM (SELECT scale, 
       dense_rank() OVER (PARTITION BY title 
             ORDER BY scale ASC) AS r 
      FROM signatures) t 
    WHERE r = 2) 
) 

但有沒有運氣。 任何人都可以看到一種方法來做到這一點?我可以分別發送這兩個查詢,然後運行一個循環並分割元素,但這不適用於半大記錄集。

此外,它應該不重要,但我使用PostgreSQL。

+1

你知道如果處理關係,`DENSE_RANK`會返回相同的值嗎?例如,您可以將三個實例並列第二名,這會導致您的分區發生悲傷...... – 2011-01-13 16:47:42

+0

@OMG。好的,但是如果我單獨運行查詢,我會得到正確的列結果。是不可能在一個陳述中分開這兩個? – Brett 2011-01-13 17:01:28

回答

1

我想你想使用LEAD窗口函數,而不是獲得兩組並試圖加入它們。這允許您在同一個窗口中引用另一行(即匹配partition by)。類似:

select title, scale/next_scale 
from (select title, scale, 
       lead(scale) over(partition by title order by scale asc) as next_scale, 
       row_number() over(partition by title order by scale asc) as agg_row 
     from signatures 
    ) agg 
where agg_row = 1; 

這裏,lead(scale)需要從scale列中的值是在同一窗口中輸出,即,在順序中的下一最規模。我們仍然需要預測row_number()並對其進行篩選,以便我們只獲取每個窗口中第一行的輸出行,即每個標題最小的行。

0

你需要給SQL一些方法來知道每列中的哪一個數字除以哪個數字。試試這個:

SELECT first.title, (first.scale/second.scale) ratio 
     FROM 
      (SELECT scale, title 
       FROM (SELECT title, scale, 
          dense_rank() OVER 
          (PARTITION BY title ORDER BY scale ASC) AS r 
         FROM signatures) t 
      WHERE r = 1) first 
INNER JOIN 
      (SELECT scale, title 
       FROM (SELECT title, scale, 
          dense_rank() OVER 
          (PARTITION BY title ORDER BY scale ASC) AS r 
         FROM signatures) t 
      WHERE r = 2) second 
     ON first.title = second.title 

由於OMG評論說,如果最終得到幾個相同的比例值,DENSE_RANK可能會給你帶來麻煩。如果適合您的邏輯,您可能希望將每個子查詢限制爲每個標題一行,或者在外部查詢中指定SELECT DISTINCT,因爲重複項將完全重複。