2015-05-04 90 views
2

我對MS SQL查詢有疑問。 我有以下我想過濾數據:在視圖上過濾

+----+----------+-------+-----------+  
| Id | Location | Store | Result |  
+----+----------+-------+-----------+  
| 1 | AB  |  1 | Executed |  
| 2 | AB  |  1 | Cancelled |  
| 3 | AB  |  2 | Executed |  
| 4 | AB  |  2 | Missing | 
| 5 | AB  |  2 | Executed |  
| 6 | CD  |  3 | Cancelled |  
| 7 | CD  |  3 | Executed |  
| 8 | EF  |  4 | Missing |  
| 9 | EF  |  4 | Cancelled |  
| 10 | GH  |  5 | Cancelled |  
+----+----------+-------+-----------+ 

我想要實現這樣的結果:

+----------+-------+----------+  
| Location | Store | Result |  
+----------+-------+----------+ 
| AB  |  1 | Executed |  
| AB  |  2 | Executed |  
| CD  |  3 | Executed |  
| EF  |  4 | Missing |  
| GH  |  5 | Cancelled|  
+----------+-------+----------+ 

以下選擇標準已被應用:

  • 如果結果包含1行,選擇該狀態(ID 10)

  • 如果結果具有相同的位置&商店:

    • 如果該組有執行的狀態1號線,挑選狀態
    • 如果該集團已多次執行的行,挑執行狀態1線問題上沒有什麼順序

每個組中的數據將始終是相同的,所以在這個例子中,一個GROUP BY選址,店面就足夠了,如果不是因爲我想要的標準。

提前致謝!

+0

對於'EF'選擇'Missing'而不是'Cancelled'的原因是什麼? – mellamokb

+0

這可以是隨機的,我只需要得到第一個結果(我沒有真正做出這個決定,但這就是我所要求的)。 –

回答

1

使用ROW_NUMBER挑一排每組合,就像這樣:

Select Location, Store, Result from 
    (Select Location, Store, Result 
    , Row_Number() over (partition by Location, Store 
      order by case Result when 'Executed' then 1 else 2 end) as RN 
from Table 
) a 
where RN = 1 

由於mellamokb注意,你可能要添加更多如果您不希望它在沒有「已執行」行時隨機選擇結果,則可以使用case語句的選項。

+0

謝謝!一個相當簡單的解決方案,爲什麼我沒有想到這一點! :d –

1

可以使用ROW_NUMBER與修改ORDER BY

WITH Cte AS(
    SELECT *, 
     RN = ROW_NUMBER() OVER(
       PARTITION BY Location, Store 
       ORDER BY 
        CASE Result 
         WHEN 'Executed' THEN 1 
         WHEN 'Missing' THEN 2 
         ELSE 3 
        END 
      )  
    FROM TestData 
) 
SELECT 
    Location, Store, Result 
FROM Cte 
WHERE RN = 1 
+0

謝謝!一個相當簡單的解決方案,爲什麼我沒有想到這一點! :D –