SQL 带有 varchar 数据类型的 PIVOT

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21630650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:00:19  来源:igfitidea点击:

PIVOT with varchar datatype

sqlsql-server-2008pivot

提问by NicoRiff

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 carchar columns. I have this table:

我正在尝试对表中的一些数据进行 PIVOT,但我不能这样做,因为我找不到使用 carchar 列的方法。我有这张桌子:

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.

我需要使用 'ug_label' 行数据作为列。由于数据类型是 VARCHAR,我不能在 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.

谢谢。

回答by Taryn

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

您仍然可以使用 PIVOT 函数来获取结果,但由于您正在聚合 a,因此varchar您必须使用maxmin

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