sql server - Ignore condition in WHERE clause when column is NULL -


i have table 1 row (with type =e) related row. have written query return count of related rows. problem there no explicit relationship (like id column row related other row). therefore trying find relationship based on multiple conditions in clause.

the problem in few cases, columns , b null (for records type = 'm'). in such cases ignore condition, use first 3 conditions determine relationship.

i have tried case statement not working expected:

select  [t1].[id],[t1].[alphaid],[t1].[type],[t1].[a],[t1].[b],[t1].[date],[t1].[serviceid]         ,(  select count(*)              mytable t2               [t1].[alphaid]=[t2].[alphaid] ,                     [t1].[date]=[t2].[date] ,                     [t1].[serviceid]=[t2].[serviceid] ,                     [t2].[a]=case when [t2].[a] null null else [t1].[a] end ,                     [t2].[b]=case when [t2].[b] null null else [t1].[b] end ,                     [t2].[type]='m'         ) totalcount  mytable t1 [t1].[type] = 'e' 

i can't ignore condition, cases date, serviceid same, it's a, b differs them. luckily a, b null, date, serviceid differs 2 records.

http://sqlfiddle.com/#!3/c98db/1

many in advance.

you join tables , use count , group counts. can join [a] , [b] if equal or null.

select [t1].[id],[t1].[alphaid],[t1].[type],[t1].[a],[t1].[b],[t1].[date],[t1].[serviceid], count([t2].[id]) mytable t1 inner join mytable t2 on [t1].[alphaid]=[t2].[alphaid] ,                     [t1].[date]=[t2].[date] ,                     [t1].[serviceid]=[t2].[serviceid] ,                     ([t2].[a]= [t1].[a] or [t2].[a] null )and                     ([t2].[b]= [t1].[b] or [t2].[b] null )and                     [t2].[type] <> [t1].[type] [t1].[type] = 'e'  group [t1].[id],[t1].[alphaid],[t1].[type],[t1].[a],[t1].[b],[t1].[date],[t1].[serviceid] 

Comments