SQL查询 - 计数并列出0而不是Null

时间:2016-11-08 14:40:00

标签: sql sql-server-2008 pivot

我有以下SQL表:

Basic structure

数据库结构&想要输出:

Data base structure & wanted output

知道查询的外观吗?我也想把0而不是Null以防万一没有结果。

BR 了Stian

4 个答案:

答案 0 :(得分:0)

由于您已修复types,因此请使用静态Conditional Aggregate

select cast([Date] as Date),
       count(case when type  = 'Maintenance' then 1 end) as [Maintenance]
       count(case when type  = 'Fault' then 1 end) as [Fault]
       count(case when type  = 'Alarm' then 1 end) as [Alarm]
       count(case when type  = 'Critical Fault' then 1 end) as [Critical Fault]
From yourtable 
Group by cast([Date] as Date)

如果type没有特定的Date,则Count汇总将返回0

答案 1 :(得分:0)

要放0而不是Null,你只需要这样做 数字和ISNULL的ISNULL(Column_Name,0)(Column_Name,'0')

答案 2 :(得分:0)

SELECT CAST([Date] AS DATE) Event_date
       sum(Case when type = 'Maintenance' then 1 else 0 end) as Maintenance
      ,sum(Case when type = 'Fault' then 1 else 0 end) as Fault
      ,sum(Case when type = 'Alarm' then 1 else 0 end) as Alarm
      ,sum(Case when type = 'Critical Fault' then 1 else 0 end) as [Critical Fault]
FROM Table
GROUP BY Cast([Date] as Date)
ORDER BY Event_date

我在这里更多的是粉丝。不需要合并,因为每个旋转列的值将为0或1+,因此将始终返回1+或0。

答案 3 :(得分:-1)

DECLARE @table table (Date datetime NOT NULL, Type varchar(50) NOT NULL);
INSERT INTO @table
VALUES
  ('08.11.2016 14:23','Maintenance'),
  ('08.11.2016 10:45','Fault'),
  ('08.11.2016 10:44','Alarm'),
  ('08.11.2016 14:23','Critical Falut'),
  ('08.11.2016 14:23','Maintenance'),
  ('08.11.2016 10:45','Fault'),
  ('08.11.2016 10:44','Alarm'),
  ('08.11.2016 14:23','Critical Falut'),
  ('07.11.2016 14:23','Maintenance'),
  ('07.11.2016 10:45','Fault'),
  ('07.11.2016 10:44','Alarm'),
  ('07.11.2016 14:23','Maintenance'),
  ('07.11.2016 10:45','Fault'),
  ('07.11.2016 10:44','Alarm')
;

-- if the value contains a space don't for get to quote it with [] i.e. [Some Value]
SELECT Date = P.DateDay, P.Maintenance, P.Fault, P.Alarm, P.[Critical Falut]
FROM (
  SELECT DateDay = CONVERT(date, Date), Date, Type
  FROM  @table
  ) AS T
PIVOT ( COUNT(Date) FOR Type IN (Maintenance, Fault, Alarm, [Critical Falut]) ) AS P
;

编辑:我很好奇为什么当它成为一个完全回答用户问题的支点时,这被拒绝投票。