比较只返回一个值和结果tsql的值的版本

时间:2017-12-21 16:23:36

标签: sql-server tsql

下面我有一个表格,它将col_A的版本与col_B的版本进行比较,如果它们相似则返回true。

Col_A | Col_B    | Col_C | 
---------------------------
val1  | versionA | true  |
val1  | versionB | false |
val1  | versionC | false |
----------------=----------
val2  | versionA | false |
val2  | versionB | false |
val2  | versionC | false |

我想要实现的目标是,如果Col_A和Col_B之间的一次比较返回true,继续前进,那么上面的表格将是:

Col_A | Col_B | 
----------------
val1  | true  |
----------------
val2  | false |

这是我的思考过程和一个示例查询,除了我真的不知道从哪里开始。

SELECT Col_A, Col_B, 
       case when Col_A = Col_B then 'true' else 'false end as Col_C --returns the first table
FROM exTable

在这种情况下,IF声明是否适合获得第二张表?

2 个答案:

答案 0 :(得分:1)

您可以使用CASE计算比较结果,然后使用MAX进行分组。

WITH exTable AS (
    SELECT * FROM (
        VALUES
            ('val1', 'val1'),
            ('val1', 'versionB'),
            ('val1', 'versionC'),
            ('val2', 'versionA'),
            ('val2', 'versionB'),
            ('val2', 'versionC')
        ) AS a (Col_A, Col_B)
)
SELECT Col_A,  
      CASE MAX(case when Col_A = Col_B then 1 else 0 end) WHEN 1 THEN 'true' ELSE 'false' END as Col_C
FROM exTable
GROUP BY Col_A

答案 1 :(得分:0)

    WITH exTable AS (
        SELECT * FROM (
            VALUES
                ('val1', 'versionA','true'),
                ('val1', 'versionB','false'),
                ('val1', 'versionC','false'),
                ('val2', 'versionA','false'),
                ('val2', 'versionB','false'),
                ('val2', 'versionC','false')
            ) AS a (Col_A, Col_B,Col_C)
    )

    --select * from exTable
    SELECT Col_A,  
          CASE MAX(case when Col_C = 'true' then 1 else 0 end) WHEN 1 THEN 'true' ELSE 'false' END as Col_C
    FROM exTable
    GROUP BY Col_A