使用pivot转入Columns

时间:2012-11-29 10:14:08

标签: sql sql-server pivot unpivot

你能帮我解决一下这个错误

  

“nvrchildgender”列的类型与UNPIVOT列表中指定的其他列的类型冲突。

表格结构:

CREATE TABLE [dbo].[tblHRIS_ChildDetails](
    [intCHID] [int],
    [intSID] [int] NOT NULL,
    [nvrChildname] [nvarchar](250) NULL,
    [nvrChildGender] [nvarchar](50) NULL,
    [dttChildDOB] [datetime] NULL,
    [nvrnominee] [nvarchar](50) NULL,
    [nvrChildOccupation] [nvarchar](250) NULL,
    [dttCreatedon] [datetime] NULL,
    [dttModifiedOn] [datetime] NULL,
    [nvrModifiedby] [nvarchar](50) NULL
) ON [PRIMARY]

查询:

select *
from
(
  select value, col+'_'+cast(rn as varchar(10)) col
  from
  (
    select nvrchildname,
      nvrchildgender,
      convert(nvarchar(10), dttchildDOB, 120) dttchildDOB,
      nvrchildoccupation,
      row_number() over(partition by intsid order by intCHID) rn
    from tblHRIS_ChildDetails
    where intsid = 463
  ) src
  unpivot
  (
    value 
    for col in (nvrchildname, nvrchildgender, dttchildDOB,  nvrchildoccupation)
  ) unpiv
) src1
pivot
(
  max(value)
  for col in ([nvrchildname_1], [nvrgender_1], 
              [dttchildDOB_1], [occupation_1], 
              [nvrchildname_2], [nvrgender_2], 
              [dttchildDOB_2], [occupation_2]) 
) piv

我无法运行此查询我认为某些演员问题请解决。

Sql fiddle

2 个答案:

答案 0 :(得分:0)

UNPIVOT列表中的列:

nvrchildname, nvrchildgender, dttchildDOB,  nvrchildoccupation

拥有不同的数据类型。

您必须确保列的类型。类似的东西:

 ...
  CAST(nvrchildname AS NVARCHAR(10)) nvrchildname,
  CAST(nvrchildgender AS NVARCHAR(10)) nvrchildgender,
  convert(nvarchar(10), dttchildDOB, 120) dttchildDOB,
  CAST (nvrchildoccupation AS NVARCHAR(10)) nvrchildoccupation
 ...

Updated SQL Fiddle Demo

答案 1 :(得分:0)

要成功完成UNPIVOT,列类型必须匹配。由于4列中有两列已经nvarchar(250)而另外两列较短,因此将它们提升为nvarchar(250)是最方便的解决方法。

select *
from
(
  select value, col+'_'+cast(rn as varchar(10)) col
  from
  (
    select nvrchildname,
      cast(nvrchildgender as nvarchar(250)) nvrgender,
      convert(nvarchar(250), dttchildDOB, 120) dttchildDOB,
      nvrchildoccupation occupation,
      row_number() over(partition by intsid order by intCHID) rn
    from tblHRIS_ChildDetails
    where intsid = 463
  ) src
  unpivot
  (
    value 
    for col in (nvrchildname, nvrgender, dttchildDOB, occupation)
  ) unpiv
) src1
pivot
(
  max(value)
  for col in ([nvrchildname_1], [nvrgender_1], 
              [dttchildDOB_1], [occupation_1], 
              [nvrchildname_2], [nvrgender_2], 
              [dttchildDOB_2], [occupation_2]) 
) piv

注意:您已将PIVOT列命名为nvrgender,但基本列为nvrchildgender。与pivot和unpivot之间的occupation列命名不匹配的问题相同。