如何从同一表中排除等于a列中的值但不等于b列中的值的行?

时间:2019-05-09 17:52:20

标签: postgresql

需要向从单个表中选择的选择语句中添加另一个条件

当前代码:

SELECT program, campaign 
FROM campaign 
WHERE substring(campaign,2,1) = '_'
AND substring(campaign,1,1) != 'X'
AND substring(campaign,1,1) != 'B'
AND substring(campaign,1,1) != 'D'
AND substring(campaign,1,1) != 'R'
AND substring(campaign,1,1) != 'T'
GROUP BY program, campaign
ORDER BY program asc;

需要添加AND substring(campaign,1,1) != 'O',但如果在程序“ ABC”中则不需要添加

1 个答案:

答案 0 :(得分:0)

您的逻辑可以简化为:

SELECT program, campaign 
FROM campaign 
WHERE 
  substring(campaign, 2, 1) = '_' 
  AND 
  substring(campaign, 1, 1) NOT IN ('X', 'B', 'D', 'R', 'T')
  AND 
  (substring(campaign, 1, 1) <> 'O' OR program = 'ABC')
GROUP BY program, campaign 
ORDER BY program asc;