0

我正在尝试进行子选择查询,但我的组中有 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 |
4

2 回答 2

1

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

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);
于 2021-04-19T13:12:43.763 回答
1

我猜你不需要那些子选择。请改用条件聚合。试试这个。

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))项目只添加匹配条件的行。

我从您的列名 ( ArretProductionJournee.HeureDebutbecome HeureDebut) 中删除了表名,因为您只使用一个表,并且查询更易于阅读。

于 2021-04-19T13:13:43.893 回答