Sql 删除子查询中的空值

Sql remove Null Values in sub queries

我正在尝试执行子 select 查询,但我的组中有 Null 值

SELECT        convert(varchar, dbo.ArretProductionJournee.DateArret, 3) , 
(select
sum (datediff(minute, ArretProductionJournee.HeureDebut, ArretProductionJournee.HeureFin)  ) 
where ArretProductionJournee.EnumArret Like 'HH')
as HH, 
(select
sum (datediff(minute, ArretProductionJournee.HeureDebut, ArretProductionJournee.HeureFin)  ) 
where ArretProductionJournee.EnumArret Like 'HI')
as HI,
(select
sum (datediff(minute, ArretProductionJournee.HeureDebut, ArretProductionJournee.HeureFin)  ) 
where ArretProductionJournee.EnumArret Like 'PS')
as PS
FROM            
dbo.ArretProductionJournee 
where dbo.ArretProductionJournee.DateArret BETWEEN '01/04/2021'and '03/04/2021'
group by ArretProductionJournee.EnumArret, convert(varchar, dbo.ArretProductionJournee.DateArret, 3)

结果如下:

我想删除那些 Null 值以获得如下结果:

---------------------------
Date Arrêt | HH | HI | PS |
---------------------------
03 / 02/ 21| 0  | 29 | 45 |

我很确定你只是想要条件聚合:

select convert(date, dbo.ArretProductionJournee.DateArret), 
       sum(case when apj.EnumArret = 'HH'
                then datediff(minute, apj.HeureDebut, apj.HeureFin)  
           end) as HH, 
       sum(case when apj.EnumArret = 'HI'
                then datediff(minute, apj.HeureDebut, apj.HeureFin)  
           end) as HI, 
       sum(case when apj.EnumArret = 'PS'
                then datediff(minute, apj.HeureDebut, apj.HeureFin)  
           end) as PS
from  dbo.ArretProductionJournee apj
where apj.DateArret between '2021-04-01' and '2021-04-03'
group by convert(date, apj.DateArret);

我想您不需要那些子 SELECT。请改用条件聚合。试试这个。

SELECT CONVERT(varchar, DateArret, 3), 
       SUM(IIF(EnumArret Like 'HH', datediff(minute, HeureDebut, HeureFin, 0)) AS HH,
       SUM(IIF(EnumArret Like 'HI', datediff(minute, HeureDebut, HeureFin, 0)) AS HI,
       SUM(IIF(EnumArret Like 'PS', datediff(minute, HeureDebut, HeureFin, 0)) AS PS,
  FROM dbo.ArretProductionJournee 
 WHERE DateArret BETWEEN '01/04/2021'and '03/04/2021'
 GROUP BY CONVERT(varchar, DateArret, 3)

之所以称为条件聚合,是因为每个SUM(IIF(condition, val, 0))项只累加符合条件的行。

我从您的列名称中删除了 table 名称(ArretProductionJournee.HeureDebut 变为 HeureDebut),因为您只使用了一个 table,而且查询更易于阅读那样。