SQL层次结构数据Pivot-Unpivot - 列类型冲突错误

时间:2013-06-10 07:18:12

标签: sql pivot hierarchy unpivot

我试图将行中的层次结构数据放入列中。我收到以下错误“列的类型”lvlCode“与UNPIVOT列表中指定的其他列的类型冲突。”

我的查询如下

;with hd (orgid, lvlCode,description, parentorgid, category)
as
(
  select orgid, lvlCode,description, parentorgid, 1 as category
  from orgunit
  where parentorgid is null
  union all
  select t1.orgid, t1.lvlCode,t1.description, t1.parentorgid, hd.category +1
  from orgunit t1
  inner join hd
    on t1.parentorgid = hd.orgid
),
unpiv as
(
  select value, 'cat_'+cast(category as varchar(5))+'_'+ col col_name
  from
  (
    select cast(orgid as varchar(17)) orgid, lvlCode,description, parentorgid, category
    from hd
  ) src
  unpivot
  (
    value for col in (orgid, lvlCode,description)
  ) un
)
select [cat_1_orgid], [cat_1_lvlCode],[cat_1_description],
                   [cat_2_orgid], [cat_2_lvlCode],[cat_2_description],
                   [cat_3_orgid], [cat_3_lvlCode],[cat_3_description],
                   [cat_4_orgid], [cat_4_lvlCode],[cat_4_description],
                   [cat_5_orgid], [cat_5_lvlCode],[cat_5_description],
                   [cat_6_orgid], [cat_6_lvlCode],[cat_6_description],
                   [cat_7_orgid], [cat_7_lvlCode],[cat_7_description]
from unpiv
pivot
(
  max(value)
  for col_name in ([cat_1_orgid], [cat_1_lvlCode],[cat_1_description],
                   [cat_2_orgid], [cat_2_lvlCode],[cat_2_description],
                   [cat_3_orgid], [cat_3_lvlCode],[cat_3_description],
                   [cat_4_orgid], [cat_4_lvlCode],[cat_4_description],
                   [cat_5_orgid], [cat_5_lvlCode],[cat_5_description],
                   [cat_6_orgid], [cat_6_lvlCode],[cat_6_description],
                   [cat_7_orgid], [cat_7_lvlCode],[cat_7_description])
) piv

1 个答案:

答案 0 :(得分:1)

尝试将lvlCode转换为varchar数据类型

...
   (
    select CAST(orgid as varchar(17)) orgid, 
           CAST(lvlCode as varchar(17)) lvlCode, 
           description, parentorgid, category
    from hd
    )
...