2010-11-07 78 views
0

作爲我在前幾天在sql-query-comparing-two-items-on-distinct-item處詢問的問題的補充,是否有可能刪除可能存在空值的可能性,其中「pers」之一未出現在'evt'中。SQL查詢 - 比較不同項目上的兩個項目 - REVISITED

輸出

 
**EVT John Paul Difference** 
A1  1  2  -1 
A2  2  3  -1 
A3  2  NULL [errors here] - ** item to be removed ** 

數據

 
**EVT PERS RANK** 
A1  John 1 
A1  Paul 2 
A1  Ringo 3 
A1  George 4 
A2  Ringo 1 
A2  John 2 
A2  Paul 3 
A2  George 4 
A3  Ringo 1 
A3  John 2 
A3  George 4 

目前代碼(感謝馬丁·史密斯)

SELECT 
     EVT, 
     MAX(CASE WHEN Pers='John' THEN Rank END) AS John, 
     MAX(CASE WHEN Pers='Paul' THEN Rank END) AS Paul, 
     MAX(CASE WHEN Pers='John' THEN Rank END) - MAX(CASE WHEN Pers='Paul' THEN Rank END) as Difference 
FROM YourTable 
WHERE Pers IN ('John','Paul') 
GROUP BY EVT 

謝謝提前

回答

1

您可以添加一個having子句:

GROUP BY EVT 
HAVING MAX(CASE WHEN Pers='John' THEN Rank END) IS NOT NULL 
     AND MAX(CASE WHEN Pers='Paul' THEN Rank END) IS NOT NULL 
1

或者

WITH NullSNotYetExcluded AS (

    --insert your SELECT statement from Martin here-- 

) 
    SELECT * FROM NullsNotYetExcluded 
    WHERE Difference IS NOT NULL; 

另一種選擇(可能更昂貴的運行)是添加

HAVING COUNT(DISTINCT Pers) = 2