在组内循环以通过比较两个列值进行过滤

时间:2017-11-24 09:35:10

标签: sql-server

   Col0 | Col1 | Col2 | Col3
    --------------------
    1, 14, Orange, 10
    2, 14, Pineapple, 10
    3, 14, Pear, 14
    4, 19, Apple, 6
    5, 19, Banana, 5

在上表中,我想在Col0中的每个组中返回一行(即14和19),其中Col1 = Col3中的值,当组中的Col1 = Col3中没有值时,则返回所有行< / p>

我期望的结果如下表所示:

Col0 | Col1 | Col2 | Col3
--------------------
1, 14, Pear, 14
2, 19, Apple, 6
3, 19, Banana, 5

提前致谢!

1 个答案:

答案 0 :(得分:1)

这很有效,但不是很优雅

DECLARE @t TABLE (Col0 INT IDENTITY, Col1 INT, Col2 NVARCHAR(15), Col3 INT)
INSERT INTO @t
(Col1, Col2, Col3)
SELECT 14, 'Orange', 10 UNION ALL
SELECT 14, 'Pineapple', 10 UNION ALL
SELECT 14, 'Pear', 14 UNION ALL
SELECT 19, 'Apple', 6 UNION ALL
SELECT 19, 'Banana', 5

;WITH cteX
AS(
    SELECT
          T.Col1
        , Col2 = MAX(T.Col2)
        , Col3 = MAX(T.Col3)
    FROM @t T
    WHERE
        T.Col1 = T.Col3
    GROUP BY
        T.Col1
)
SELECT
      Col0 = ROW_NUMBER()OVER(ORDER BY (SELECT NULL))
    , Z.Col1
    , Z.Col2
    , Z.Col3
FROM
(
    SELECT 
          X.Col1
        , X.Col2
        , X.Col3
    FROM cteX X
    UNION
    SELECT
          T.Col1
        , T.Col2
        , T.Col3
    FROM @t T
    WHERE
        T.Col1 <> T.Col3
    AND Col1 NOT IN (SELECT Y.Col1 FROM cteX Y)
) Z

输出

Col0 | Col1 | Col2 | Col3
--------------------
1, 14, Pear, 14
2, 19, Apple, 6
3, 19, Banana, 5