根据列的MAX()过滤UNION结果

时间:2014-07-11 07:21:18

标签: sql-server

我有两个查询,他们的结果集与UNION结合在一起。

我正在尝试根据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 |
+-----------------+----------+--------------+

1 个答案:

答案 0 :(得分:3)

试试这个:

;with cte as
( --Your union),

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

select * from filtered
where rank = 1