使用分组依据将null转换为0或保持为null

时间:2019-01-11 00:51:55

标签: sql

我的桌子是这样的:

ID identity school location character percent
1  teacher  Gateways Leeds  nice 80
1  teacher  Gateways Leeds  good 20
2  student  Seva    Coventry   nice  100
2  student  Seva    Coventry   good  
3  professor Regent   London nice
3  professor Regent   London good

在第一个ID中,具有[nice]和[good]的同一组(身份,学校,位置)中[percent]列的总和为100。

在第二个ID中,将[percent]中的一个单元格设置为null,但我希望将其设置为0

在第3个ID中,两个单元格均为空。我不让它转换为0。

我的问题是第二和第三ID:

我如何设置条件,如果另一个单元格为100,则让一个单元格为0,或者如果另一个单元格为空,则将两个单元格都保持为null?

ID identity school location character percent
1  teacher  Gateways Leeds  nice 80
1  teacher  Gateways Leeds  good 20
2  student  Seva    Coventry   nice  100
2  student  Seva    Coventry   good  0
3  professor Regent   London nice
3  professor Regent   London good

非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以通过这种方式在MS SQL Server中使用。

 Select * into #temp  from 
( Select 1 as ID,          'teacher'  as   [identity],  'Gateways' as school,  
'Leeds'     as [Location] ,'nice' as character,  80  as [Percent]
union all Select 1 as ID,   'teacher'  as  [identity],  'Gateways' as school,  
'Leeds'     as [Location] ,'good' as character,  20  as [Percent]
 union all Select 2 as ID,   'student'  as  [identity],  'Seva'    as school ,  
'Coventry'   as [Location] ,'nice' as character, 100  as [Percent]
 union all Select 2 as ID,   'student'  as  [identity],  'Seva'    as school ,  
 'Coventry'   as [Location] ,'good' as character, null as [Percent] 
 union all Select 3 as ID,   'professor' as [identity], 'Regent'  as school ,  
 'London'       as [Location] ,'nice' as character, null as [Percent]
  union all Select 3 as ID,   'professor'as [identity], 'Regent'  as school ,  
 'London'       as [Location] ,'good' as character, null as [Percent]) z 



update  t   
set [Percent] = 0 
from 
#temp t 
 where [Percent] is null and exists (select id, [identity], school, [location], 
 sum([percent]) totalPercent from #temp t2 
                                  where t2.id = t.id and t2.[identity] = t.[identity] 
 and t2.school = t.school 
                                  and t.[Location] = t2.[Location] 
                                  group by id, [identity], school, [location] 
                                  having  sum([percent]) = 100) 

我假设它应该在相同的ID,位置,身份和学校内,并且如果整个组的总和为100,则它将在组中出现空值的任何地方更新为0。

输出:

Select * from #temp 

enter image description here