根据条件获取单行

时间:2019-07-25 18:49:47

标签: sql sql-server tsql

我有一些简单的选择查询,例如:

 SELECT
                 [c].[column1]
                , [c].[column2]
                 FROM [Customer] AS [c]
                     INNER JOIN ...

所以我对主表进行左连接为:

LEFT JOIN [Communication] AS [com] ON  [c].[CustomerGuid] = [com].[ComGuid]

此关系与其1到*相关,一个客户可以进行多次通信

因此,我要根据条件选择值1或2:

条件:

(如果ComTypeKey(来自通信)表具有一行值为3的行,而另一行具有值为4的行,则返回1,然后返回0

所以我尝试类似的事情:

SELECT
                 [c].[column1]
                , [c].[column2]
                , IIF([com].[ComTypeKey] = 3 AND [com].[ComTypeKey] = 4,1,0)
                 FROM [Customer] AS [c]
                     INNER JOIN ...
                      LEFT JOIN [Communication] AS [com] ON  [c].[CustomerGuid] = [com].[ComGuid]

但是它抛出了我两行,因为在交流中有两行。我的期望值是,如果我的条件为真,则只获得值为1的一行

2 个答案:

答案 0 :(得分:0)

如果您有多行,则需要GROUP BY,然后计算相关键并减去1得到(1,0)

SELECT
    [c].[column1]
  , [c].[column2]
  ,  COUNT(CASE WHEN [ComTypeKey] IN (3,4) THEN 1 END) - 1  as FLAG_CONDITION
FROM [Customer] AS [c]
INNER JOIN ...
LEFT JOIN [Communication] AS [com] 
  ON  [c].[CustomerGuid] = [com].[ComGuid]
GROUP BY 
    [c].[column1]
  , [c].[column2]

答案 1 :(得分:0)

我不确定自己是否了解。

这将从字面上查找该CustomerGuid的值3和4是否都存在,并且在这种情况下仅选择其中一个-否则就不过滤掉任何记录。

如果这不是您想要的,则提供具有预期结果的示例数据将消除歧义。

SELECT Field1,
       Field2,
       ...
       FieldN
  FROM (SELECT TMP.*,
               CASE WHEN hasBothValues = 1 THEN 
                           ROW_NUMBER() OVER ( PARTITION BY CustomerGuid ORDER BY 1 )
                    ELSE 1
                END AS iterim_rn
          FROM (SELECT TD.*,
                       MAX(CASE WHEN Value1 = '3' THEN 1 ELSE 0 END) OVER
                         ( PARTITION BY CustomerGuid ) *
                       MAX(CASE WHEN Value1 = '4' THEN 1 ELSE 0 END) OVER
                         ( PARTITION BY CustomerGuid ) AS hasBothValues
                  FROM TEST_DATA TD
               ) TMP
       ) TMP2
 WHERE interim_rn = 1