0

需要一些帮助才能从同一列中搜索某些组合。

表值:

COLUMN1  COLUMN2 COLUMN3
WF1      Email   AA
WF1      Letter  BB
WF2      Email   AA
WF2      Letter  BB
WF2      Pen     CC

如果(第 1 列 = WF1)+(第 2 列 = 电子邮件和信函)+(第 2 列 = 信函和第 3 列 = BB),则打印“N”:

 COLUMN1         COLUMN2     COLUMN3
    **WF1**      **Email**   AA
    **WF1**      **Letter**  **BB**
    WF2          Email       AA
    WF2          Letter      BB
    WF2          Pen         CC

我尝试了以下查询但卡住了:

select 
  case 
    when max(result) = 2 
      then 
        case when instrument in ('Email', 'Letter') and gem_contract_type = 'BB'
         then 'N'
        else 'Y'
        end
  else
    'Y'
  end 
   from(
select column2, column3, 
count(*) over (partition by column1 order by column2) result
  from 
(select * from table1 where column = 'WF1')
  );
4

1 回答 1

1

如果这不是完整的答案,我希望它至少是朝着正确方向迈出的一步......

首先,这将返回同时具有和in的所有Column1值的列表:Email LetterColumn2

SELECT Column1
FROM myTable
WHERE Column2 IN ('Email', 'Letter')
GROUP BY Column1
HAVING COUNT(DISTINCT Column2) = 2

您可以将其加入您的表格以获得我认为您想要的结果:

WITH EmAndLet AS (
  SELECT Column1
  FROM myTable
  WHERE Column2 IN ('Email', 'Letter')
  GROUP BY Column1
  HAVING COUNT(DISTINCT Column2) = 2
)
SELECT
  MyTable.Column1,
  MyTable.Column2,
  MyTable.Column3,
  CASE WHEN EmAndLet.Column1 IS NOT NULL AND MyTable.Column3 = 'BB'
    THEN 'N'
    ELSE 'Y'
    END
FROM myTable
LEFT JOIN EmAndLet ON myTable.Column1 = EmAndLet.Column1

左加入时,如果没有相应的EmAndLet行,则为EmAndLet.Column1空。如果有对应的行,EmAndLet.Column1就会有一个值,并且会通过上面语句IS NOT NULL中的测试。CASE希望这是有道理的:)

于 2013-10-03T17:57:54.850 回答