Oracle Select查询可在同一列上查找组合

时间:2013-10-03 15:59:53

标签: sql oracle

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

表值:

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')
  );

1 个答案:

答案 0 :(得分:1)

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

首先,这将返回Column1中包含Email Letter的所有Column2值的列表:

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测试。希望这是有道理的:)