sql server创建动态列运行时

时间:2019-01-30 08:15:55

标签: sql sql-server

在sql server中创建动态查询以创建列 例如

    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;

然后添加5列

对于eaxmple @NoOFcolumns int = 10 如何默认添加10列

1 个答案:

答案 0 :(得分:1)

您可以从distinct表中获取top (@NoOFcolumns) customerrewards,以生成动态数据透视。

您可以尝试使用动态PIVOT,如下所示。

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)

注意:我没有亲自执行查询,但是我认为它应该可以工作。