2014-07-11 154 views
1

我有兩個查詢,它們的結果集合在一起使用UNION。基於MAX()篩選列結果

我想根據FilterColumn的MAX()過濾出行,但我無法弄清楚如何做到這一點。

+-----------------+----------+--------------+ 
| PropDescription | PropCode | FilterColumn | 
+-----------------+----------+--------------+ 
| 476SADDR1  | Finland |   2 | 
| 477SADDR1  | Sweden |   2 | 
| 1SADDR1   | 2038  |   1 | 
| 2SADDR1   | 2030  |   1 | 
| 3SADDR1   | 15  |   1 | 
| 4SADDR1   | 00000002 |   1 | 
| 6SADDR1   | 500  |   1 | 
| 8SADDR1   | 556  |   1 | 
| 9SADDR1   | 821  |   1 | 
+-----------------+----------+--------------+ 

SELECT 
    PropDescription 
    , PropCode 
    , FilterColumn 
FROM 
    (SELECT DISTINCT 
     CASE 
      WHEN PL.Type = 11 
       THEN PL.ADDR 
      ELSE P.ADDR 
      END AS N'PropDescription' 
     ,CASE 
      WHEN PL.TYPE = 3 
       THEN P.CODE 
      ELSE LPA.Value 
      END AS N'PropCode' 
     , 2 AS FilterColumn 
    FROM PROPERTY PL 
    INNER JOIN PROPLIST LP2 ON PL.ID = LP2.PropList 
    INNER JOIN PROPERTY P ON LP2.Property = P.ID 
    INNER JOIN PropAttribute LPA ON LPA.PropList = PL.ID 
    WHERE 1 = 1 
     AND PL.ID IN (SELECT Property from PROPLIST where PropList IN (47,46)) 
     AND P.TYPE = 3 

    UNION ALL 

    SELECT DISTINCT 
     CASE 
      WHEN PL.Type = 11 
       THEN PL.ADDR 
      ELSE P.ADDR 
      END AS N'PropDescription' 
     ,CASE 
      WHEN PL.TYPE = 3 
       THEN P.CODE 
      ELSE LPA.Value 
      END AS N'PropCode' 
     , 1 AS FilterColumn 
    FROM PROPERTY PL 
    INNER JOIN PROPLIST LP2 ON PL.ID = LP2.PropList 
    INNER JOIN PROPERTY P ON LP2.Property = P.ID 
    LEFT JOIN PropAttribute LPA ON LPA.PropList = PL.ID 
    WHERE 1 = 1 
    AND PL.ID IN (SELECT Property from PROPLIST where PropList IN (1,2,3,4)) 
    AND PL.TYPE = 3 
    ) AS ResultSet 

我知道這很簡單,但我現在不能弄明白。

預期成果是:

+-----------------+----------+--------------+ 
| PropDescription | PropCode | FilterColumn | 
+-----------------+----------+--------------+ 
| 476SADDR1  | Finland |   2 | 
| 477SADDR1  | Sweden |   2 | 
+-----------------+----------+--------------+ 
+0

所以將你的預期產出的樣子,根據樣本數據您提供什麼? –

+0

嗯,從我讀我很想念你怎麼想的過濾器對FilterColumn工作附加條件....直到現在我明白這 選擇 PropDescription ,PropCode ,FilterColumn FROM (YourSubQuery) GROUP通過PropDescription,PropCode HAVING FilterColumn = MAX(FilterColumn) –

+0

@ shree.pat18更新我的問題與預期的輸出。 –

回答

3

試試這個:

;with cte as 
(--Your union), 

filtered as 
(*, rank() over (order by filtercolumn desc) rank from cte) 

select * from filtered 
where rank = 1 
+1

是的,排名..就是這樣!我知道我之前使用過一些東西,但不記得是什麼。 –

+0

@RaduGheorghiu不用擔心,我們都會被這些事情困擾! –