No record count in PIVOT

  • Hi,

    I have the following query to count the number of employees per costcenter using the pivot command.

    The @Columns parameter declares these costcenters.

    The query shows results but the problem is that the count is zero for every costcenter! When I do "count(*)", it has the same problem.

    Even a night of proper sleep didn't brought up a light.

    What's wrong with the count in the pivot command?

    I think it's simple quite but I haven't figured it out yet ...

    Thanks for your help!

    declare @Columns varchar(max)

    declare @Query nvarchar(max)

    select @Columns = isnull(@Columns + ',[' + kstplcode + ']', '[' + kstplcode + ']')

    from kstpl

    where LEFT(kstplcode, 1) in ('B', 'S')

    set @Query =

    N'

    declare @DaysMinus int

    set @DaysMinus = 8

    select''No of employees per '' + convert(varchar(10), PeriodEnd, 105) as KPI,

    ' + @Columns + '

    from

    (

    selecth.res_id as Resource,

    pd.eddatum as PeriodEnd,

    kp.oms25_0 as Costcenter

    fromhumres h

    left outer join perdat pd on convert(varchar(10), GETDATE()- @DaysMinus, 105) = convert(varchar(10), pd.eddatum, 105)

    left outer join kstpl kp on h.costcenter = kp.kstplcode

    whereisnull(h.ldatuitdienst, getdate()+1) > pd.eddatum - @DaysMinus -and h.res_id > 5000

    ) as data

    pivot(count(data.Resource) for data.Costcenter in ('+ @Columns +')) as pivottable

    '

    exec(@Query)

  • it looks like there is an extra minus sign in your query at whereisnull(h.ldatuitdienst, getdate()+1) > pd.eddatum - @DaysMinus -

    Other than that with out some sample data it will be hard to dianose what the issue is.

    The other issue is that i may look at hard coding the @DaysMinus or concantenate that value in to the dynamic sql query instead of declaring a variable in the dynamic SQL


    For faster help in answering any problems Please read How to post data/code on a forum to get the best help - Jeff Moden[/url] for the best way to ask your question.

    For performance Issues see how we like them posted here: How to Post Performance Problems - Gail Shaw[/url]

    Need to Split some strings? Jeff Moden's DelimitedSplit8K[/url]
    Jeff Moden's Cross tab and Pivots Part 1[/url]
    Jeff Moden's Cross tab and Pivots Part 2[/url]

  • Sorry, I omitted a remark at the end of the line, but I left one minus-sign there. My fault! My original query is correct and does not have this minus-sign.

    I'm still wondering what it is ....

  • Hi

    You may want to check you @columns variable. It could have a comma at the beginning

  • There is a comma! As far as I know the syntax is correct for the columns variable. Or not?

  • michielbijnen (11/12/2012)


    There is a comma! As far as I know the syntax is correct for the columns variable. Or not?

    As an example

    select 'Count IsPrimary', [0], [1]

    from (select isprimary, blockid from block) b

    pivot (

    count(blockid)

    for isprimary in ([0],[1])

    ) pWill work

    Based on a quick glance at you procedure I'm guessing you producing something like

    select 'Count IsPrimary',, [0], [1]

    from (select isprimary, blockid from block) b

    pivot (

    count(blockid)

    for isprimary in (,[0],[1])

    ) pWhich will generate a syntax error.

    If you trim the leading comma off the columns you query should start working. But that is a guess as I can't test it. You may want to change exec(@query) to select @query and post the actual query that is being generated.

  • michielbijnen (11/12/2012)


    There is a comma! As far as I know the syntax is correct for the columns variable. Or not?

    every thing in the dynamic sql is correct since the extra "-" is from a comment (you deal with the leading comma a little differently than i would but it works and that is what matters). so now in order to figure out what is going on we are going to need sample data. try running all the queries and make sure you are getting the expected results. Try running SELECT @Columns after you build it and running the base select of your pivot. those are the areas where a problem can occur since the syntax of your dynamic pivot looks fine.


    For faster help in answering any problems Please read How to post data/code on a forum to get the best help - Jeff Moden[/url] for the best way to ask your question.

    For performance Issues see how we like them posted here: How to Post Performance Problems - Gail Shaw[/url]

    Need to Split some strings? Jeff Moden's DelimitedSplit8K[/url]
    Jeff Moden's Cross tab and Pivots Part 1[/url]
    Jeff Moden's Cross tab and Pivots Part 2[/url]

  • mickyT (11/12/2012)


    michielbijnen (11/12/2012)


    There is a comma! As far as I know the syntax is correct for the columns variable. Or not?

    As an example

    select 'Count IsPrimary', [0], [1]

    from (select isprimary, blockid from block) b

    pivot (

    count(blockid)

    for isprimary in ([0],[1])

    ) pWill work

    Based on a quick glance at you procedure I'm guessing you producing something like

    select 'Count IsPrimary',, [0], [1]

    from (select isprimary, blockid from block) b

    pivot (

    count(blockid)

    for isprimary in (,[0],[1])

    ) pWhich will generate a syntax error.

    If you trim the leading comma off the columns you query should start working. But that is a guess as I can't test it. You may want to change exec(@query) to select @query and post the actual query that is being generated.

    nope he handles the leading "," with the initial ISNULL. the OP does not initialize the @columns variable so NULL + ',SOMETHING' is NULL and the ISNULL function returns the second value (which does not have the leading ",").


    For faster help in answering any problems Please read How to post data/code on a forum to get the best help - Jeff Moden[/url] for the best way to ask your question.

    For performance Issues see how we like them posted here: How to Post Performance Problems - Gail Shaw[/url]

    Need to Split some strings? Jeff Moden's DelimitedSplit8K[/url]
    Jeff Moden's Cross tab and Pivots Part 1[/url]
    Jeff Moden's Cross tab and Pivots Part 2[/url]

  • capnhector (11/12/2012)


    nope he handles the leading "," with the initial ISNULL. the OP does not initialize the @columns variable so NULL + ',SOMETHING' is NULL and the ISNULL function returns the second value (which does not have the leading ",").

    My bad sorry ... didn't read it properly:ermm:

  • Sorry!!

    A bit of a beginners fault :blush: .... the field "kstplcode" in the @columns variable was not the same as the field "oms25_0" in the data-query! :doze:

    Thanks for your help, anyway!

  • What's now the best way to add a grand total column at the end of the cross tab?

  • I would Suggest using a CTE to hold the pivot table then select your data and union it to a totals query.

    This will get you close, i changed your dynamic sql a bit to use my tally table to give me some output i could use so you will have to modify this slightly.

    declare @Columns varchar(max)

    declare @Query nvarchar(max)

    DECLARE @SumColumns NVARCHAR(MAX)

    select @Columns = isnull(@Columns + ',[' + CAST(N AS VARCHAR) + ']', '[' + CAST(N AS VARCHAR) + ']')

    from Tally

    where N < 9

    select @SumColumns = isnull(@SumColumns + ',SUM([' + CAST(N AS VARCHAR) + '])', 'SUM([' + CAST(N AS VARCHAR) + '])')

    from Tally

    where N < 9

    SELECT @Query =

    N'

    declare @DaysMinus int

    set @DaysMinus = 8;

    WITH BasePvt AS (

    select''No of employees per '' + convert(varchar(10), PeriodEnd, 105) as KPI,

    ' + @Columns + '

    from

    (

    selecth.res_id as Resource,

    pd.eddatum as PeriodEnd,

    kp.oms25_0 as Costcenter

    fromhumres h

    left outer join perdat pd on convert(varchar(10), GETDATE()- @DaysMinus, 105) = convert(varchar(10), pd.eddatum, 105)

    left outer join kstpl kp on h.costcenter = kp.kstplcode

    whereisnull(h.ldatuitdienst, getdate()+1) > pd.eddatum - @DaysMinus - and h.res_id > 5000

    ) as data

    pivot(count(data.Resource) for data.Costcenter in ('+ @Columns +')) as pivottable

    )

    SELECT KPI,

    ' + @Columns + ' FROM BasePivot

    UNION

    SELECT ''Totals'', ' + @SumColumns + 'FROM BasePivot

    '

    SELECT @Query


    For faster help in answering any problems Please read How to post data/code on a forum to get the best help - Jeff Moden[/url] for the best way to ask your question.

    For performance Issues see how we like them posted here: How to Post Performance Problems - Gail Shaw[/url]

    Need to Split some strings? Jeff Moden's DelimitedSplit8K[/url]
    Jeff Moden's Cross tab and Pivots Part 1[/url]
    Jeff Moden's Cross tab and Pivots Part 2[/url]

  • Thanks a lot, but this adds a total row to the pivot.

    What I would like to have is a total column at the end of the row that contains the total for that row.

    I'm a bit confused about the results that I come across in Google. It didn't work out so far with my query.

    Could you help me out with this one?

    Thanks!

  • same concept as the total rows except instead of sum and you would use a second column variable to dynamically create column1 + column2 ... then instead of using a CTE you would instead use the working pivot table and just add that calculated column to the end of your select.


    For faster help in answering any problems Please read How to post data/code on a forum to get the best help - Jeff Moden[/url] for the best way to ask your question.

    For performance Issues see how we like them posted here: How to Post Performance Problems - Gail Shaw[/url]

    Need to Split some strings? Jeff Moden's DelimitedSplit8K[/url]
    Jeff Moden's Cross tab and Pivots Part 1[/url]
    Jeff Moden's Cross tab and Pivots Part 2[/url]

  • Thanks for your reply!

    I do something wrong but not sure what ...

    I think the @SumColumns variable is not correct.

    Hope you can help me out? Thanks

    Here is my query:

    DECLARE @Columns VARCHAR(MAX)

    DECLARE @SumColumns VARCHAR(MAX)

    DECLARE @Query nVARCHAR(MAX)

    SELECT @Columns = ISNULL(@Columns + ',[' + kstplcode + ']', '[' + kstplcode + ']')

    FROM kstpl

    WHERE Enabled = 1

    SELECT @SumColumns = ISNULL(@Columns + ',[' + @Columns + ']', '[' + @Columns + ']')

    FROM kstpl

    WHERE Enabled = 1

    SET @Query =

    N'

    DECLARE @DaysMinus INT

    SET @DaysMinus = 18;

    --WITH BasePivot as

    (

    SELECT''No of employees per '' + convert(VARCHAR(10), PeriodEnd, 105) as KPI,

    ' + @Columns + '

    FROM

    (

    SELECTh.res_id as Resource,

    pd.eddatum as PeriodEnd,

    h.costcenter as Costcenter

    --kp.oms25_0 as CComs

    FROMhumres h

    LEFT OUTER JOIN perdat pd ON convert(VARCHAR(10), GETDATE()- @DaysMinus, 105) = convert(VARCHAR(10), pd.eddatum, 105)

    LEFT OUTER JOIN kstpl kp ON h.costcenter = kp.kstplcode

    WHEREISNULL(h.ldatuitdienst, getdate()+1) > pd.eddatum - @DaysMinus /* Job runs on the last day of period */

    AND h.res_id > 5000

    GROUP BY pd.eddatum, h.costcenter, h.res_id

    ) as data

    PIVOT(count(data.Resource) FOR data.Costcenter IN (' + @Columns + ')) as pivottable

    )

    SELECT

    --KPI, ' + @Columns + ' FROM BasePivot

    KPI, ' + @Columns + ', ' + @SumColumns + ' FROM pivottable

    '

    EXEC (@Query)

Viewing 15 posts - 1 through 14 (of 14 total)

You must be logged in to reply to this topic. Login to reply