如何在SQL SERVER中使用具有不同条件的SELECT语句

时间:2017-08-23 12:44:00

标签: sql sql-server tsql

我有一个sql server数据库表,其中包含以下信息:

v.x

我想提取符合以下条件的报告:

TEST Priority [tolerance %] [% Diff] 
24  critical    5    0.000000000000000

21  critical    5    12.000000000000000
20  critical    5    0.000000000000000
17  critical    5    0.189035916824100
19  critical    5    0.000000000000000
18  critical    5    20.000000000000000

29  critical    5    0.000000000000000
121 critical    5    0.862068965517200
28  critical    5    0.000000000000000
30  critical    5   -1.030927835051500
34  critical    5   -0.080671184252900
32  critical    5    0.000000000000000
33  critical    5    0.000000000000000
35  medium     15    0.000000000000000
31  critical    5    0.000000000000000
36  critical    5    0.000000000000000
37  critical    5   -7.246376811594200
38  high       10    0.000000000000000
39  medium     15   30.197604790419100
40  medium     15   -0.529100529100500
41  critical    5   0.831255195344900
44  critical    5   -0.141843971631200
43  critical    5   -0.147167034584200
42  critical    5   -9.478468899521500
48  medium     15   0.000000000000000
45  medium     15   0.116144018583000
46  medium     15   -2.469135802469100
47  medium     15   0.000000000000000
49  critical   5    0.000000000000000
51  low       20    0.000000000000000
53  high      10    -1.420118343195200
52  high      10    -23.125786163522000
54  medium    15    0.000000000000000

这是我的代码:

1. priority = critical and [% Diff] is either >= 5 or <= -5 
2. priority = high and [% Diff] is either >= 10 or <= -10
3. priority = low and [% Diff] is either >= 20 or <= -20
4. priority = medium and [% Diff] is either >= 15 or <= -15  

似乎在这里遗漏了什么,有人可以帮我吗?有人建议使用案例陈述但不确定这是如何起作用的?

2 个答案:

答案 0 :(得分:1)

你在第一组条件周围缺少一对括号:

Select   * 
From     Table1
Where    (Priority = 'critical' And ([% Diff] >= 5 or [% Diff ] <= -5 ))
Or       (Priority = 'high'     And ([% Diff ] >= 10 or [% Diff] <= -10 ))
Or       (Priority = 'LOW'      And ([% Diff ] >= 20 or [% Diff ] <= -20 ))
Or       (Priority = 'MEDIUM'   And ([% Diff ] >= 15 or [% Diff ] <= -15 ))

答案 1 :(得分:-1)

你可以像这样改进你的代码 - &gt;

Select * from Table1
where (Priority = 'critical' and [% Diff] not Between  -5 and 5 )
OR (Priority = 'high' and [% Diff ] not between -10 and 10 )
OR (Priority = 'LOW' and [% Diff ] not between -20 and 20 )
OR (Priority = 'MEDIUM' and [% Diff ] not between -15 and 15)