结合比较运算符

时间:2017-01-23 14:24:27

标签: sql sql-server

请告知如何更改以下代码以提取[execution_status]的记录,例如'failure',同时[has_messages]如'0'。我正在尝试不同的方式,并且所有时间结果都包括has_messages'0'和'1':(。非常感谢!!

SELECT * 
FROM (SELECT [id]
            ,[type]
            ,[created]
            ,dateadd(s, created/1000, '19700101')as date_created
            ,[state]
            ,[execution_status]
            ,[has_messages]
      FROM [databasename].[tablename] 
      WHERE type like 'AccessRequest' 
        AND not state like 'Initialize') as jaro 
WHERE date_created between '2016-12-01' and '2016-12-31'
ORDER by date_created

2 个答案:

答案 0 :(得分:3)

以下是一堆建议。首先,我会修改表格以获得日期的计算列:

alter table tablename add date_created as (dateadd(second, created/1000, '19700101'));

这将允许您向列添加索引,这可以加快查询速度。然后,你应该修正你的日期比较(阅读Aaron Bertrand的优秀解释What do BETWEEN and the Devil Have In Common?):

select t.*
from tablename t
where (date_created >= '2016-12-01' and date_created < '2017-01-01') and
      ((type like 'AccessRequest' AND state not like 'Initialize') or
       (execution_status like 'failure' and has_messages like '0')
      )

补充意见:

  • 不要对数字值使用like。如果has_messages是数字,只需使用=
  • 虽然可以使用like进行字符串比较,但很多人会同意=的意图更清晰。
  • 此查询仍会获得has_message不是0的值,因为这些行符合原始条件。

答案 1 :(得分:0)

这个怎么样:

SELECT * 
FROM (SELECT
               id
              ,type
              ,created
              ,dateadd(s, created/1000, '19700101') AS date_created
              ,state
              ,execution_status
              ,has_messages
        FROM databasename.tablename 
       WHERE (type = 'AccessRequest' 
         AND state != 'Initialize')
          OR (execution_status = 'failure' 
         AND has_messages = 0)
     ) AS jaro
WHERE date_created >= '2016-12-01' <= '2016-12-31'
ORDER BY date_created