0

我有这个 unpivot 表,我希望删除应用于它的过滤器。

DECLARE @colsPivot AS NVARCHAR(MAX),
    @colsUnpivot as NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)



select @colsPivot = STUFF((SELECT distinct ',' + QUOTENAME(year(EcoDate)) 
                    from PhdRpt.RptCaseEco
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('PhdRpt.RptCaseEco') 
         and C.name Like 'Net%'
         for xml path('')), 1, 1, '')


set @query 
  = 'select *
      from
      (
        select reportruncaseid, year(Ecodate) as EcoYear, val, col
        from phdrpt.rptcaseeco

        unpivot
        (
          val
          for col in ('+ @colsUnpivot +')
        ) u
      ) x1
      pivot
      (
        max(val)
        for ecoyear in ('+ @colspivot +')

      ) p ORDER BY reportruncaseid'


exec(@query)

该表以前有效,因为所有列的前缀都是“Net”,但现在还有其他列被过滤掉,因为它们不以“Net”开头。我试图删除 --- 和 C.name Like 'Net%' --- 但我不断收到这些错误:

Msg 8167, Level 16, State 1, Line 10 The type of column "EcoDate" conflicts with the type of other columns specified in the UNPIVOT list.
Msg 207, Level 16, State 1, Line 4 Invalid column name 'reportruncaseid'.
Msg 207, Level 16, State 1, Line 4 Invalid column name 'Ecodate'.

这是桌子的样子
桌子

4

1 回答 1

2

可以删除用于获取 UNPIVOT 列列表的过滤器,但如果存在您不想 UNPIVOT 的列,则需要排除它们:

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('PhdRpt.RptCaseEco') 
         and C.name not in ('reportruncaseid', 'Ecodate')
         for xml path('')), 1, 1, '')

这会将所有列返回到 unpivot,除了 reportruncaseidand Ecodate(或您不希望 unpivot 的其他列)。所以完整的查询将是:

DECLARE @colsPivot AS NVARCHAR(MAX),
    @colsUnpivot as NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @colsPivot = STUFF((SELECT distinct ',' + QUOTENAME(year(EcoDate)) 
                    from PhdRpt.RptCaseEco
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('PhdRpt.RptCaseEco') 
         and C.name not in ('reportruncaseid', 'Ecodate')
         for xml path('')), 1, 1, '')

set @query 
  = 'select *
      from
      (
        select reportruncaseid, year(Ecodate) as EcoYear, val, col
        from phdrpt.rptcaseeco

        unpivot
        (
          val
          for col in ('+ @colsUnpivot +')
        ) u
      ) x1
      pivot
      (
        max(val)
        for ecoyear in ('+ @colspivot +')

      ) p ORDER BY reportruncaseid'

exec(@query);

此外,如果您有不同数据类型的列,则必须在应用 unpivot 之前将它们转换为相同的数据类型。

于 2013-04-29T16:29:10.007 回答