1

in sql server create dynamic query to create columns for example

    declare @NoOFcolumns int=5
select name, [Col1], [col2], [col3], [col4], [col5]
from
(
  select c.name,
    cr.description,
    r.typeid
  from customers c
  left join rewards r
    on c.id = r.customerid
  left join customerrewards cr
    on r.typeid = cr.typeid
) x
pivot
(
  count(typeid)
  for description in ([Col1], [col2], [col3], [col4], [col5])
) p;

then add 5 columns

for eaxmple @NoOFcolumns int=10 how to add 10 columns by default

1

1 Answer 1

1

You can get the distinct top (@NoOFcolumns) from you customerrewards tables for generating the dynamic pivot.

You can try using dynamic PIVOT like following.

DECLARE @NoOFcolumns int=5

DECLARE @cols AS NVARCHAR(max) = Stuff((SELECT DISTINCT TOP (@NoOFcolumns)  ', ' 
                                 + Quotename([description] ) 
         FROM   customerrewards 
         FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''); 

DECLARE @query AS NVARCHAR(max) =
                 'select *
                        from
                        (
                            select c.name,
                            cr.description,
                            r.typeid
                            from customers c
                            left join rewards r
                            on c.id = r.customerid
                            left join customerrewards cr
                            on r.typeid = cr.typeid
                        ) x
                        pivot
                        (
                            count(typeid)
                            for description in IN ('+@cols+') 
                        ) p;'

EXECUTE(@query)

Note: I have not executed the query myself, but I feel it should work.

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe even change the select * to select name' + @cols +' I was about to suggest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.