如何使用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
我的结果是这样的:
答案
这应该做你想要的。
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