-2

你能帮我解决这个错误吗

“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 小提琴

4

2 回答 2

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
 ...

更新的 SQL Fiddle 演示

于 2012-11-29T10:24:51.633 回答
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. occupation枢轴和非枢轴之间的列命名不匹配也存在同样的问题。

于 2012-11-29T10:26:30.740 回答