简体   繁体   English

从 SQL 查询中过滤数据

[英]Filter the data from the SQL Query

In the below table, I need to exclude CategoryID=1002 and Gender='KIDS' record from the table and return other records.在下表中,我需要从表中排除CategoryID=1002Gender='KIDS'记录并返回其他记录。

+------+--------+
|  ID  | Gender |
+------+--------+
| 1001 | MENS   |
| 1002 | MENS   |
| 1001 | WOMENS |
| 1002 | WOMENS |
| 1001 | KIDS   |
| 1002 | KIDS   |
+------+--------+

Expected results:预期成绩:

+------+--------+
|  ID  | Gender |
+------+--------+
| 1001 | MENS   |
| 1002 | MENS   |
| 1001 | WOMENS |
| 1002 | WOMENS |
| 1001 | KIDS   |
+------+--------+

You could use a CASE expression as您可以使用CASE表达式作为

SELECT *
FROM
(
  VALUES
  (1001,    'MENS'),
  (1002,    'MENS'),
  (1001,    'WOMENS'),
  (1002,    'WOMENS'),
  (1001,    'KIDS'),
  (1002,    'KIDS')
) T(Id, Gender)
WHERE CASE WHEN ID = 1002 AND Gender = 'KIDS' THEN 1 ELSE 0 END = 0;

Online Demo 在线演示

I don't recommend using case expressions in the where clause, because that can affect the optimizer.我不建议在where子句中使用case表达式,因为这会影响优化器。

This is easily expressed as boolean logic:这很容易表达为 boolean 逻辑:

where not (CategoryID = 1002 and Gender = 'KIDS')

or:或者:

where CategoryID <> 1002 or Gender <> 'KIDS'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM