Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

sql - PIVOT with varchar datatype

I′m trying to PIVOT some data in a table, but I cannot do it because I do not find the way to do it using varchar columns. I have this table:

enter image description here

And what I need is this:

enter image description here

I need to use the 'ug_label' row data as columns. As the datatype is VARCHAR, I cannot use an agregate function inside the PIVOT.

I think I might need something like this:

SELECT *
FROM
(SELECT [c_id]
      ,[c_lname] as [Apellido]
      ,[c_fname] as [Nombre]
      ,[c_nick_name] as [documento]      
      ,[ut_text] 
      ,f.ug_label
  FROM [pegasys].[dbo].[cardholder] c
  inner join [pegasys].[dbo].[udftext] u on c.c_id = u.ut_cardholder_id 
  inner join [pegasys].[dbo].[udfgen] f on u.ut_udfgen_id = f.ug_id) AS S  
PIVOT
(
    UT_TEXT
    FOR
    [UG_LABEL]
    IN ([Torre], [Cuit], [Empresa], [Departamento])
) as s

Can someone help me??.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can still use the PIVOT function to get the result but since you are aggregating a varchar you have to use either max or min:

SELECT *
FROM
(
  SELECT [c_id]
      ,[c_lname] as [Apellido]
      ,[c_fname] as [Nombre]
      ,[c_nick_name] as [documento]      
      ,[ut_text] 
      ,f.ug_label
  FROM [pegasys].[dbo].[cardholder] c
  inner join [pegasys].[dbo].[udftext] u on c.c_id = u.ut_cardholder_id 
  inner join [pegasys].[dbo].[udfgen] f on u.ut_udfgen_id = f.ug_id
) d  
PIVOT
(
    max(ut_text)
    FOR UG_LABEL IN ([Torre], [Cuit], [Empresa], [Departamento])
) p

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...