2014-11-06 214 views
0

我在查詢中使用了16個表,並試圖通過應用以下新更改來優化查詢。因此,我們不能使用group或union子句,因爲由於性能問題而無法應用於現有查詢。刪除條件重複值

我正在尋找通過排名/計數/排數分區意味着行級解決方案,如果可能的話。

select * FROM (
SELECT 'HA' as CODE,0 AS SR FROM DUAL UNION ALL 
SELECT 'HA' as CODE,0 AS SR FROM DUAL UNION ALL 
SELECT 'OF' as CODE,0 AS SR FROM DUAL UNION ALL 
SELECT 'AC' as CODE,1 AS SR FROM DUAL UNION ALL 
SELECT 'OF' as CODE,0 AS SR FROM DUAL UNION ALL 
SELECT 'OF' as CODE,1 AS SR FROM DUAL UNION ALL 
SELECT 'OF' as CODE,1 AS SR FROM DUAL UNION ALL 
SELECT 'XY' as CODE,1 AS SR FROM DUAL UNION ALL 
SELECT 'XY' as CODE,1 AS SR FROM DUAL UNION ALL 
SELECT 'HA' as CODE,1 AS SR FROM DUAL UNION ALL 
SELECT 'OF' as CODE,1 AS SR FROM DUAL) 
ORDER BY SR 

隨着上述查詢的示例數據欲:

  1. 保持所有行,其中SR = 0
  2. 刪除SR = 1行,其中代碼值中存在(SR = 0)

例如,SR = 1的「AC」行被包括在內,因爲不存在SR = 0的「AC」行;並且SR = 1的「HA」行被刪除,因爲存在SR = 0的「HA」行。

所需輸出這樣的數據:

HA 0 
OF 0 
HA 0 
OF 0 
XY 1 
XY 1 
AC 1 

回答

1

你可以添加一個子查詢和分析min()

select code, sr 
from (
    select code, sr, min(sr) over (partition by code) as min_sr 
    from (
    <your query> 
) 
) 
where sr = 0 
or (sr = 1 and min_sr = 1) 
order by sr; 

對於每一行子查詢得到最低的SR的附加列代碼跨所有行。外部查詢然後對這些進行過濾,以便SR = 1的行只在該代碼的最小值也爲1時才被保留;即SR = 0時該代碼不存在行。

有了您的虛擬數據,讓:使用CTE與您的數據,並顯示以及在子查詢額外的分析,分列

CODE   SR 
---- ---------- 
OF   0 
OF   0 
HA   0 
HA   0 
XY   1 
XY   1 
AC   1 

SQL Fiddle demo

您也可以將其簡化爲where sr = min_sr,但將它分成兩個子句可能會使邏輯和規則更清晰。

+0

謝謝Alex。你的答案正在起作用。 – sandip 2014-11-06 13:41:55

0

我們也可以嘗試以下方法,把上面的子查詢到一個WITH

WITH s AS (
    SELECT 'HA' as CODE,0 AS SR FROM DUAL UNION ALL 
    SELECT 'HA' as CODE,0 AS SR FROM DUAL UNION ALL 
    SELECT 'OF' as CODE,0 AS SR FROM DUAL UNION ALL 
    SELECT 'AC' as CODE,1 AS SR FROM DUAL UNION ALL 
    SELECT 'OF' as CODE,0 AS SR FROM DUAL UNION ALL 
    SELECT 'OF' as CODE,1 AS SR FROM DUAL UNION ALL 
    SELECT 'OF' as CODE,1 AS SR FROM DUAL UNION ALL 
    SELECT 'XY' as CODE,1 AS SR FROM DUAL UNION ALL 
    SELECT 'XY' as CODE,1 AS SR FROM DUAL UNION ALL 
    SELECT 'HA' as CODE,1 AS SR FROM DUAL UNION ALL 
    SELECT 'OF' as CODE,1 AS SR FROM DUAL) 
SELECT code, sr FROM s s1 -- 's1' is the table alias 
WHERE s1.sr = 0 
    OR (s1.sr = 1 
    AND NOT EXISTS (SELECT 1 FROM s s2 -- 's2' is the table alias 
         WHERE s2.code = s1.code 
         AND s2.sr = 0)) 

結果:

HA 0 
HA 0 
OF 0 
OF 0 
AC 1 
XY 1 
XY 1 

我我是否認爲這是比@Alex更具可讀性分普爾的答案,但。但它確實避免了分析功能。