根据SQL中的多个参数过滤值(多行)

时间:2019-02-14 10:22:50

标签: sql postgresql

感谢您的帮助!我是SQL的新手。

我尝试检索 offers__c 列的值等于'a'但也可以等于'a'和{{1}的用户}和/或'w'和/或'x'和/或'y'和/或'z')。

每个用户可以有多个行(带有'''a''w''x''y''z') -唯一的通用ID。 (他们必须始终有''。) 我想检索这些行(如果存在),但是没有其他行。

例如:如果用户有多个行,其中一列等于'a',并且(另一行包含'a',另一行等于'w',则我不会要检索它。

'p'

通过该查询,我还获得了SELECT customerAccount__c, offers__c, Id FROM Table1 WHERE customerAccount__c IN ( SELECT customerAccount__c FROM Table1 WHERE offers__c = 'a' OR ( offers__c = 'a' AND ( offers__c = 'w' OR offers__c = 'x' OR offers__c = 'y' OR offers__c = 'z' OR offers__c = '' ) ) ) 'p'之类的值。我想排除其他与我要求的值不匹配的值。

编辑:

表1:

'r'

输出:

customerAccount__c    offers__c         Id
        -                 -              -
        1                'a'        0015800001RzCebAAF
        1                'w'            ...
        1                'x'       
        3                'y'
        2                'a'
        2                'w'
        3                'z'
        3                'a'
        4                'a'
        5                'a'
        5                'w'
        5                'p'      

在这个例子中,我得到customerAccount__c offers__c Id - - - 1 'a' a0G5808300xWGxQEAG 1 'w' a0G5737300xWGxqEAG 1 'x' a0G5809990xWGxqEAG 2 'a' ... 2 'w' 3 'y' 3 'z' 3 'a' 4 'a' 5 'a' 0015800001RzCCbAAF 5 'w' 0015800002RzDAbAAF 5 'p' 0015800003REDEbAAF 的{​​{1}}(5)。但是我不要。由于offers__c,我只想要'p'(1)并排除(5)。

:请注意,我不知道表中的所有不同值(因为有130多个潜在值),例如。 customerAccount__c'p''p'等。

期望的输出:

'r'

1 个答案:

答案 0 :(得分:1)

描述有些不清楚,但听起来像是:

SELECT * FROM table1 AS t
WHERE EXISTS
         (SELECT 1 FROM table1 AS t1
          WHERE t.customerAccount__c = t1.customerAccount__c
            AND t1.offers__c = 'a')
  AND NOT EXISTS
         (SELECT 1 FROM table1 AS t2
          WHERE t.customerAccount__c = t2.customerAccount__c
            AND t2.offers__c NOT IN ('a', 'w', 'x', 'y', 'z', ''));

稍微说明一下,这将从表中选择满足两个条件的所有行:

  1. 存在与customerAccount__c相同的offers__c = 'a'的行
  2. 没有与customerAccount__coffers__c'a''w',{ {1}}和'x'