如何使用pivot Sql Query在0中转换Null值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用pivot Sql Query在0中转换Null值相关的知识,希望对你有一定的参考价值。

这是我的问题,我正在做的是显示现场执行官每日工作的成绩单。所有记录都是正确的但我想在标题中显示日期或用0填充空值。

[DECLARE @Pivot_Column [nvarchar](max); 
DECLARE @Query [nvarchar](max);SELECT @Pivot_Column= COALESCE(@Pivot_Column+',','')+ 
QUOTENAME([DAY])  FROM (SELECT DISTINCT datepart(day,statusupdatedate) as [Day] 
FROM tbl_trn_RawData where StatusUpdateDate is not null and DATENAME(MONTH,StatusUpdateDate)='July') 
 Tab SELECT @Query='SELECT [FE Name], '+@Pivot_Column+'FROM(select [FE name],count(StatusByFE) as [Total],
  datepart(day,statusupdatedate) as [Day] FROM tbl_trn_RawData where StatusUpdateDate is not null  group by
   [FE name],statusupdatedate) Tab1 PIVOT(SUM([Total]) FOR [Day] IN ('+@Pivot_Column+')) AS Day ORDER BY Day.
   [FE name]'EXEC  sp_executesql  @Query 

我的结果是这样的:

This is my result review please tell me where i need to correct

答案

这应该做你想要的。

create table tbl_trn_RawData([FE name] varchar(50),StatusUpdateDate date, StatusByFE int)
go
insert into  tbl_trn_RawData
values ('Ananesh Raghav','2018-07-12',3),
('Ananesh Raghav','2018-07-14',5),
('Lokendra Raghav','2018-07-14',1),
('Narinder Singh','2018-07-12',2),
('Narinder Singh','2018-07-13',5)
go
DECLARE @Pivot_Column [nvarchar](max); 
DECLARE @Pivot_ColumnNotNull [nvarchar](max); 
DECLARE @Query [nvarchar](max);
SELECT @Pivot_Column= COALESCE(@Pivot_Column+',','')+ QUOTENAME([DAY]),
       @Pivot_ColumnNotNull= COALESCE(@Pivot_ColumnNotNull+',','')+ QUOTENAME([DAY])+'=coalesce('+QUOTENAME([DAY])+',0)'  
FROM (SELECT DISTINCT datepart(day,statusupdatedate) as [Day] 
FROM tbl_trn_RawData 
where StatusUpdateDate is not null 
and DATENAME(MONTH,StatusUpdateDate)='July') 
 Tab 

 SELECT @Query='
 ;with p as (
    SELECT top 100 percent [FE Name], '+@Pivot_Column+
    'FROM(select [FE name],count(StatusByFE) as [Total],
            datepart(day,statusupdatedate) as [Day] 
            FROM tbl_trn_RawData where StatusUpdateDate is not null  
            group by [FE name],statusupdatedate) Tab1 
    PIVOT(SUM([Total]) 
    FOR [Day] IN ('+@Pivot_Column+')) AS Day 
    ORDER BY Day.[FE name]
  ) 
  SELECT [FE Name], '+@Pivot_ColumnNotNull+' FROM p'EXEC  sp_executesql  @Query 

以上是关于如何使用pivot Sql Query在0中转换Null值的主要内容,如果未能解决你的问题,请参考以下文章

谁能帮我将 Access Query 转换为 MS SQL Query

在 SQL 中使用“Pivot”将行转换为列

如何在以下格式上使用 Pivot

BigQuery 标准 SQL 如何将行转换为列

在 Sql Server 中使用 Pivot/unpivot 将单行转换为单列

sql server如何通过pivot对数据进行行列转换(进阶)