需要一些帮助才能从同一列中搜索某些组合。
表值:
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')
);
答案 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
测试。希望这是有道理的:)