NULL Values in Dynamic Pivot Query

时间:2015-09-14 15:29:44

标签: sql sql-server dynamic pivot

I am looking to display the NULL values as blank spaces or dashes to make the resulting data set easier to read as the date range can vary. For example, for a date range of 10 days I could receive NULL values for 5 out of the 10 days for a person's hours. I just want those NULL values to be blank if a person has no hours for that day.

I have seen examples of ISNULL being used on pivot tables, but not a dynamic pivot table. I'm wondering how to specify the NULL replacement for my dynamic list of dates filled into @PivotColumns.

In my query example below, I have omitted non-relevant code such as joins and other informational columns, etc.

SELECT 
@PivotColumns = COALESCE(@PivotColumns + ',','') + QUOTENAME(CONVERT(varchar(20),eff_date,110))
FROM
(SELECT DISTINCT 
    eff_date
FROM 
    timept
WHERE 
    eff_date
        BETWEEN
    @StartDate AND @EndDate) AS TimePivot
ORDER BY
eff_date

SET
@TimeQuery =
    'WITH Hours AS (
        SELECT 
            ,tp.person_id
            ,tp.hours
            ,tp.task_code
            ,tp.eff_date
            ,SUM(tp.hours) OVER(PARTITION BY tp.person_id, edr.name, tp.task_code, tp.comments ORDER BY tp.task_code) AS sum_hours
        FROM
            tables
        WHERE
            tp.eff_date BETWEEN ''' + @StartDate + ''' AND ''' + @EndDate + '''
            )
        SELECT
            *
        FROM
            Hours
            PIVOT
                (SUM(hours)
                    FOR 
                eff_date
                    IN 
                ('+@PivotColumns+')) as p'

EXEC sp_executesql @TimeQuery

1 个答案:

答案 0 :(得分:1)

试试这个:

@TimeQuery =
' WITH Hours AS (
    SELECT 
        ,tp.person_id
        ,ISNULL(tp.hours, '''')
        ,tp.task_code
        ,ISNULL(tp.eff_date, '''')
        ,SUM(tp.hours) OVER(PARTITION BY tp.person_id, edr.name, tp.task_code, tp.comments ORDER BY tp.task_code) AS sum_hours
    FROM
        tables
    WHERE
        tp.eff_date BETWEEN ''' + @StartDate + ''' AND ''' + @EndDate + '''
        )
    SELECT
        *
    FROM
        Hours
        PIVOT
            (SUM(hours)
                FOR 
            eff_date
                IN 
            ('+ @PivotColumns +')) as p'