2013-12-16 222 views
2

下面是oracle SQL,我想在Teradata格式中對其進行更改。teradata中的QUALIFY ROW_NUMBER

SELECT branch_code, 
    branch_no, 
    c_no, 
    cd_type 
FROM (
    SELECT branch_code, 
     branch_no, 
     c_no, 
     cd_type, 
     * * RANK() OVER (
      PARTITION BY c_no ORDER BY cd_type 
      ) RANK * * 
    FROM (
     SELECT branch_code, 
      branch_no, 
      c_no, 
      MIN(cd_type) cd_type 
     FROM EMPLOYEE 
     WHERE S_CODE = 'C' 
      AND (branch_no) NOT IN (
       SELECT branch_code 
       FROM DEPARTMENT 
       WHERE branch_code = 'ABC' 
       ) 
     ) 
    ) 
WHERE RANK = 1 

我已經使用QUALIFY作爲如下。

SELECT branch_code, 
    branch_no, 
    c_no, 
    cd_type 
FROM (
    SELECT branch_code, 
     branch_no, 
     c_no, 
     cd_type, 
     * * QUALIFY ROW_NUMBER() OVER (
      PARTITION BY c_no ORDER BY cd_type 
      ) * * RANK 
    FROM (
     SELECT branch_code, 
      branch_no, 
      c_no, 
      MIN(cd_type) cd_type 
     FROM EMPLOYEE 
     WHERE S_CODE = 'C' 
      AND (branch_no) NOT IN (
       SELECT branch_code 
       FROM DEPARTMENT 
       WHERE branch_code = 'ABC' 
       ) 
     ) 
    ) 
WHERE RANK = 1 

但是,得到錯誤「預期之間的事情,與出線。

我們可以把select語句資格嗎?

回答

2

你可能簡化現有查詢,因爲這是沒有有效的Oracle SQL( Inline View中沒有GROUP BY)。另外,您還可以在NOT IN中比較branch_nobranch_code

否則埃德吉布斯回答可以進一步簡化爲:

SELECT branch_code, 
    branch_no, 
    c_no, 
    MIN(cd_type) cd_type 
FROM EMPLOYEE 
WHERE S_CODE = 'C' 
    AND (branch_no) NOT IN (
     SELECT branch_no 
     FROM DEPARTMENT 
     WHERE branch_code = 'ABC' 
     ) 
GROUP BY branch_code, 
    branch_no, 
    c_no 
QUALIFY 
    RANK() 
    OVER (PARTITION BY c_no 
     ORDER BY MIN(cd_type) = 1 

如果branch_no被定義爲可爲空,你也應該重寫NOT INNOT EXISTS

2

通常情況下,像RANK計算倒數第二個分析的價值,加盟後過濾和GROUP BYHAVING。分析值後唯一做的是ORDER BY。這就是爲什麼在Oracle中,您需要將RANK放入內部查詢中,然後在外部查詢中測試其值。在Teradata中,QUALIFY在執行後分析函數和ORDER BY之前,這意味着您不需要外部查詢來測試RANK值。

我沒有進入到今天的Teradata,所以這個查詢未經測試,但我喜歡把它很接近:

SELECT branch_code, 
    branch_no, 
    c_no, 
    cd_type 
FROM (
    SELECT branch_code, 
     branch_no, 
     c_no, 
     MIN(cd_type) cd_type 
    FROM EMPLOYEE 
    WHERE S_CODE = 'C' 
     AND (branch_no) NOT IN (
      SELECT branch_code 
      FROM DEPARTMENT 
      WHERE branch_code = 'ABC' 
     ) 
) 
QUALIFY ROW_NUMBER() OVER (PARTITION BY c_no ORDER BY cd_type) = 1 
+1

由於它是有益的。 – navku