具有多个条件的SQL查询

时间:2017-04-05 13:23:35

标签: sql sql-server

我有下面提到的查询,它显示范围内和范围外的结果。如果P1超出范围且P2在范围内,则应显示P1超出范围值,在P2中应显示空白;如果P2超出范围且P1在范围内,则应在P1中显示空白和P1的价值。

SELECT  DATEANDTIME,[P1],[P2]
FROM    REPORTDATA
WHERE   [P1] < '85' OR [P1] > '95' OR [P2] < '85' OR [P2] > '95'

我尝试了这个查询,但没有按预期工作

预期输出(https://pugjs.org/language/conditionals.html):

+ ------------- + ------ + ------ +
| Date and Time | Param1 | Param2 |
|               | Range  | Range  |
|               | 35-50  | 70-80  |
+ ------------- + ------ + ------ +
| 12:35:00      |        | 82     |
| 12.36         |        | 65     |
| 12:37         | 17     | 85     |
| 12:38         | 52     |        |
| 12:39         | 25     |        |
| 14:40         |        | 52     |
+ ------------- + ------ + ------ +

1 个答案:

答案 0 :(得分:0)

不确定您的期望,但请查看以下内容:

SELECT  DATEANDTIME,[P1],[P2]
FROM    REPORTDATA
WHERE   ([P1] < '85' OR [P1] > '95') 
   OR ([P2] < '85' OR [P2] > '95')

或者您可以尝试使用CASE查询:

SELECT  DATEANDTIME,[P1],[P2],
    CASE WHEN ([P1] < '85' OR [P1] > '95') OR ([P2] < '85' OR [P2] > '95') THEN 'value out of range'
        ELSE 'value in range'
    END AS INFO
FROM    REPORTDATA

测试给出正确的输出:

declare @p1 int = 86
declare @p2 int = 100

SELECT  getdate(),@p1,@p2,
    CASE WHEN (@p1 < '85' OR @p1 > '95') OR (@p2 < '85' OR @p2 > '95') THEN 'value out of range'
        ELSE 'value in range'
    END AS INFO