Как настроить предложение WHERE для выбора всех записей без Premium = 0 при передаче значения NULL в качестве параметра в операторе SQL - PullRequest
0 голосов
/ 08 марта 2019

Результат должен вернуть:

  • Если @reasonID = 1 Мне нужно выбрать только те политики, которые имеют reasonID = 211
  • Если @reasonID = 2, мне нужно выбрать только те политики, которые имеют reasonID <> 211, включая reasonID IS NULL
  • Если @reasonID = NULL Мне нужно выбрать все политики, включая NULL и Premium <> 0

Приведенный ниже пример работает для @reasonID = 1 и @reasonID = 2:

@ reasonID = 1

enter image description here* * 1030

@ reasonID = 2

enter image description here

Но как я могу настроить предложение WHERE, чтобы выбрать все строки, когда @reasonID = NULL? Потому что он возвращает политики с Premium = 0, которые мне не нужны.

@ reasonID = NULL

enter image description here

declare @TempTable1 table (ControlNo int, PolicyNumber varchar(50), Premium money)

insert into @TempTable1 
values (1, 'Pol1', 100), (2, 'Pol2', 0), (3, 'Pol3', 50), (4, 'Pol4', 0),
       (5, 'Pol5', 70), (6, 'Pol6', 0), (7, 'Pol7', 30)

declare @TempTable2 table (ControlNo int, PolicyNumber varchar(50), reasonID int)

insert into @TempTable2 
values (1, 'Pol1', 5), (2, 'Pol2', NULL), (3, 'Pol3', 211),
       (4, 'Pol4', 8), (5, 'Pol5', 211), (6, 'Pol6', NULL),
       (7, 'Pol7', 3)

--select * from @TempTable1
--select * from @TempTable2

--Here I input @reasonID  parameter
declare @reasonID int = NULL

select
    T2.ControlNo, T2.PolicyNumber, T1.Premium, T2.reasonID 
from    
    @TempTable1 T1
inner join 
    @TempTable2 T2 on t1.ControlNo = T2.ControlNo
where   
    T1.Premium <> 0
    and (case when reasonID = 211 then 1 else 2 end = @reasonID) --works for @reasonID = 1 or @reasonID = 2
     or (@reasonID IS NULL) --does not work

Но должно быть так:

enter image description here

Можно ли каким-либо образом изменить предложение WHERE для достижения желаемого результата без использования предложения HAVING или GROUP BY?

Ответы [ 2 ]

1 голос
/ 08 марта 2019

Я думаю, вы, возможно, пропустили добавление одной круглой скобки.Кроме того, я изменил ваш оператор case в условии where, потому что ваше условие else будет учитывать также нулевые значения.Поскольку у вас есть или условие для нулей, это не имеет значения прямо сейчас.Я предположил, что вы, возможно, не хотите иметь нулевое условие в вашем выражении case, поэтому я изменил его. Я не видел Policy 8 в ваших входных данных, поэтому он не генерирует выходное значение 8. rest - то же самое.

declare @TempTable1 table (ControlNo int,PolicyNumber varchar(50), Premium money)
insert into @TempTable1 values (1,'Pol1', 100),
                               (2,'Pol2', 0),
                               (3,'Pol3', 50),
                               (4,'Pol4', 0),
                               (5,'Pol5', 70),
                               (6,'Pol6', 0),
                               (7, 'Pol7',30)

declare @TempTable2 table (ControlNo int,PolicyNumber varchar(50), reasonID int)
insert into @TempTable2 values (1,'Pol1', 5),
                              (2,'Pol2', NULL),
                              (3,'Pol3', 211),
                              (4,'Pol4', 8),
                              (5,'Pol5', 211),
                              (6,'Pol6', NULL),
                              (7,'Pol7',3)
--select * from @TempTable1
--select * from @TempTable2

--Here I input @reasonID  parameter
declare @reasonID int = NULL

select  T2.ControlNo,T2.PolicyNumber, T1.Premium, T2.reasonID 
from    @TempTable1 T1
        inner join @TempTable2 T2 on t1.ControlNo = T2.ControlNo
where   T1.Premium <> 0
        and ((case when reasonID = 211 then 1 
         when isnull(reasonID,'') not in (211,'') then 2 end = @reasonID) --works for @reasonID = 1 or @reasonID = 2
            OR (@reasonID IS NULL)) --does not work (added parentheses)

Вывод: теперь он не приносит премию <> 0

ControlNo   PolicyNumber    Premium reasonID
1            Pol1             100.00    5
3            Pol3              50.00    211
5             Pol5             70.00    211
7             Pol7             30.00    3
0 голосов
/ 08 марта 2019

Я считаю, что вам нужно что-то вроде этого:

select *
from @TempTable1 t1
join @TempTable2 t2 on t1.ControlNo = t2.ControlNo
where t1.Premium <> 0
    and (
            (@reasonID is null)
            or
            (@reasonID = 1 and t2.reasonID = 211)
            or
            (@reasonID = 2 and (t2.reasonID <> 211 or t2.reasonID is null))
        )

Данные:

declare @TempTable1 table (ControlNo int,PolicyNumber varchar(50), Premium money)
insert into @TempTable1 values (1,'Pol1', 100),
                               (2,'Pol2', 0),
                               (3,'Pol3', 50),
                               (4,'Pol4', 0),
                               (5,'Pol5', 70),
                               (6,'Pol6', 0),
                               (7, 'Pol7',30),
                               (8, 'Pol8',10)

declare @TempTable2 table (ControlNo int,PolicyNumber varchar(50), reasonID int)
insert into @TempTable2 values (1,'Pol1', 5),
                              (2,'Pol2', NULL),
                              (3,'Pol3', 211),
                              (4,'Pol4', 8),
                              (5,'Pol5', 211),
                              (6,'Pol6', NULL),
                              (7,'Pol7',3),
                              (8,'Pol8',null)

Для @reasonID = null:

ControlNo   PolicyNumber Premium               ControlNo   PolicyNumber reasonID
----------- ------------ --------------------- ----------- ------------ -----------
1           Pol1         100.00                1           Pol1         5
3           Pol3         50.00                 3           Pol3         211
5           Pol5         70.00                 5           Pol5         211
7           Pol7         30.00                 7           Pol7         3
8           Pol8         10.00                 8           Pol8         NULL

Для @reasonID = 1:

ControlNo   PolicyNumber Premium               ControlNo   PolicyNumber reasonID
----------- ------------ --------------------- ----------- ------------ -----------
3           Pol3         50.00                 3           Pol3         211
5           Pol5         70.00                 5           Pol5         211

Для @reasonID = 2:

ControlNo   PolicyNumber Premium               ControlNo   PolicyNumber reasonID
----------- ------------ --------------------- ----------- ------------ -----------
1           Pol1         100.00                1           Pol1         5
7           Pol7         30.00                 7           Pol7         3
8           Pol8         10.00                 8           Pol8         NULL
...