当另一列包含 SQl 中的值时如何过滤掉列值

How to filter out a column value when another column contains a value in SQl

如果另一列中存在值,我如何过滤掉一列中的值?我正在尝试删除 CODE 列中的所有 C,如果它在 Description 列中带有“-”。

CODE |  Description
A      -
A      -
B      -
B      -
C      stuff
C      -

在 'CODE' 列中,如果描述 = '-',我想删除值 'C'。

最终结果看起来像下面的 table,删除了 C & -。

CODE |  Description
A      -
A      -
B      -
B      -
C      stuff

请注意,描述列是使用 CASE WHEN 的自定义字段。

在 excel 中,我只创建一个虚拟条件列,然后过滤掉 'C' &'-'。我不确定如何在 SQL 中执行此操作。

尝试:

SELECT CODE, Description 
FROM your_table_name 
WHERE (CODE Not Like 'C' And Description Not Like '-');

此外,我建议保留相同案例的 field/column 名称,例如 'Code' 和 'Description' 或 'CODE' 和 DESCRIPTION'。这是一个更好的做法。

一种表达方式是 not:

where not (code = 'C' and Description = '-')

这似乎与您表达的逻辑非常接近。

这相当于:

where code <> 'C' or Description <> '-')

请注意,这两种解决方案都假定 codedescription 不是 NULL。也可以对其进行修改以处理该问题,但根据问题中的数据,这似乎没有必要。

    select 
    t1.Code,
    t1.Description
    from MyTable t1
    where t1.code not in (select code from MyTable where Description not like '-') 
    union All
    select * from MyTable
    where Description not like '-'
    order by code asc

小学:

结果: