sql - 使用多个类似条件选择查询

标签 sql sql-server sql-server-2008 sql-like

下面是现有的 ms sql server 2008 报表查询。

SELECT
    number, batchtype, customer, systemmonth, systemyear, entered, comment, totalpaid
FROM
    payhistory LEFT OUTER JOIN agency ON
        payhistory.SendingID = agency.agencyid      
WHERE
    payhistory.batchtype LIKE 'p%' AND
    payhistory.entered >= '2011-08-01 00:00:00.00' AND
    payhistory.entered <  '2011-08-15 00:00:00.00' AND
    payhistory.systemmonth = 8 AND
    payhistory.systemyear = 2011 AND
    payhistory.comment NOT LIKE 'Elit%'

结果将如下所示:

number  batchtype   customer    systemmonth systemyear  entered     comment         totalpaid
6255756 PC      EMC1106     8       2011        12:00:00 AM DP From - NO CASH       33
5575317 PA      ERS002      8       2011        12:00:00 AM MO-0051381526 7/31      20
6227031 PA      FTS1104     8       2011        12:00:00 AM MO-10422682168 7/30     25
6232589 PC      FTS1104     8       2011        12:00:00 AM DP From - NO CASH       103
2548281 PC      WAP1001     8       2011        12:00:00 AM NCO DP $1,445.41        89.41
4544785 PCR     WAP1001     8       2011        12:00:00 AM NCO DP $1,445.41        39

我想做的是修改查询,以排除客户类似于“FTS%”和“EMC%”且 batchtype =“PC”的记录。正如您在结果集中看到的那样,有客户类似于 FTS% 和 batchtype = 'PA' 的记录。我想在结果中保留这些记录。如果有任何想法,我将不胜感激。

最佳答案

您的查询包含上下字符串比较目标的混合。据我所知,SQL Server 默认情况下不区分大小写;是否有可能这就是使您的查询绊倒的原因?根据 this answer 检查整理.

编辑:根据您更新的问题,您不能只使用在前面使用 NOT 的 AND 子句吗? 换句话说,添加一个“AND not (x)”子句,其中“x”是定义要排除的记录的条件?您需要嵌套客户测试,因为它是一个 OR。 例如:

... payhistory.comment NOT LIKE 'Elit%'
AND not ((customer like 'FTS%' or customer like 'EMC%') AND batchtype = 'PC')

作为旁注,我相信 LIKE 子句在某些情况下可能意味着低效的表扫描(但 not all ),因此如果此查询将用于对性能敏感的角色,您可能需要检查查询计划并优化表以适应。

关于sql - 使用多个类似条件选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7758266/

相关文章:

sql - Excel VBA - 存储过程 (SQL Server)

Mysql - 如何退出/退出存储过程

php - mysqli 更新不起作用

sql - 在创建数据库中使用参数

sql - 根据另一列中的日期将列中的日期更改 30

sql - 处理 UNPIVOT 中的 NULL 值

mysql - SQL 案例语句

sql-server - 向表sql server添加一列零

sql - 使用外键,我可以在复合主键中引用固定值吗?

sql - 在 SQL Server 中创建具有空值的插入查询