替换SQL Pivot查询中的空值

时间:2019-02-26 08:09:59

标签: sql-server sqlite

我有一个存储过程接受日期和月份作为参数,从而得出每月出勤表。为了处理空值,我想将空值替换为“零”。

存储过程

ALTER procedure [dbo].[sps_AttendanceShowModified] @mon int, @year int
As begin DECLARE @cols  AS NVARCHAR(MAX)=''; DECLARE @query AS
NVARCHAR(MAX)='';

set @query =  'SELECT * from  (
     select  e.Name,a.WorkHours,DAY(a.AttendaceDate) AS d1 from  Attendace a,employee e where e.EmpID=a.EmpID and
MONTH(a.AttendaceDate)= ' + CONVERT(VARCHAR(12), @mon)+ ' AND
YEAR(a.AttendaceDate)= ' + CONVERT(VARCHAR(12), @year)+ ' ) src pivot 
(
    max(WorkHours) for d1 in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30])
) piv'

execute(@query) end

1 个答案:

答案 0 :(得分:0)

您需要将SELECT *更改为使用nullISNULL处理COALESCE,如下所示。

SELECT name,COALESCE([1],0) AS [1],COALESCE([2],0) AS [2] ....其他列

如果您想显示'Zero',则在这种情况下,您需要先使用CASTCONVERT,然后再应用COALESCE,如下所示。

COALESCE(cast([1] as varchar),'Zero') as [1]