我的SQL Server查询未返回预期结果

时间:2018-07-13 18:26:39

标签: sql-server sql-server-2008 filtering multiple-conditions

添加条件时,我的SQL Server查询未返回预期结果。 我遇到这种情况的部分将被忽略:

chartTime >= CONVERT(datetime, '2013-06-01 00:00:00' )

它不会显示'2013-06-01 00:00:00'之后的所有记录,但是当它是查询的唯一条件时才起作用

完整查询:

SELECT TOP(100) 
    CONVERT(smalldatetime, ROUND(CAST([chartTime] AS float) * 24.0, 0) / 24.0)[chartTime], 
    [interventionId], [terseForm], [verboseForm], 
    [attributeId], [encounterId]
FROM
    [CISReportingDB].[dbo].[PtAssessment]
WHERE
    chartTime >= CONVERT(datetime, '2013-06-01 00:00:00') 
    AND interventionId IN (SELECT [interventionId] 
                           FROM [CISReportingDB].[dbo].[PtAssessment]
                           WHERE interventionId IN (6659, 9899, 11870)) 
    OR verboseForm LIKE 'sibil. exp%' 
    OR attributeId LIKE '67194%'

谢谢

1 个答案:

答案 0 :(得分:2)

我认为您的where子句中需要一些括号...

WHERE
    chartTime >= CONVERT(datetime, '2013-06-01 00:00:00') 
    AND 
    (interventionId IN (SELECT [interventionId] 
                           FROM [CISReportingDB].[dbo].[PtAssessment]
                           WHERE interventionId IN (6659, 9899, 11870)) 
    OR verboseForm LIKE 'sibil. exp%' 
    OR attributeId LIKE '67194%')

这将返回行,chartTime >= '2013-06-01 00:00:00'您的日期...和其中之一退出。如果没有括号,则您的AND / OR逻辑有冲突,这意味着它将返回verboseForm LIKE 'sibil. exp%' OR attributeId LIKE '67194%'

否则,您需要确保确实有适合您的过滤的行……这意味着interventionId是6659,9899或11870或verboseForm LIKE 'sibil. exp%' OR attributeId LIKE '67194%'

最后,IN子句是多余的...您只需列出一次值即可:

WHERE
    chartTime >= CONVERT(datetime, '2013-06-01 00:00:00') 
    AND 
    (interventionId IN (6659, 9899, 11870) 
    OR verboseForm LIKE 'sibil. exp%' 
    OR attributeId LIKE '67194%')