如何透视SQL 2005中文本类型的简单重复数据
我做了一些搜索,找到了关于如何透视数字和求和的信息,但我还没有看到我可以透视文本的地方 简而言之,我们有一张桌子,看起来有点像这样如何透视SQL 2005中文本类型的简单重复数据,sql,pivot,Sql,Pivot,我做了一些搜索,找到了关于如何透视数字和求和的信息,但我还没有看到我可以透视文本的地方 简而言之,我们有一张桌子,看起来有点像这样 PlanID AreaAbbrev AreaDescription GoalText 10133 Rec Recreation Johnny is good at... 10133 Community Community Part Johnny is currently going
PlanID AreaAbbrev AreaDescription GoalText
10133 Rec Recreation Johnny is good at...
10133 Community Community Part Johnny is currently going...
10133 Employment Employment Johnny is currently employed at...
10144 Rec Recreation Sammy is good at...
10144 Community Community Part Sammy is currently going...
10144 Employment Employment Sammy is currently employed at...
你可以看到总有三个不同的区域,它们重复。你可以看到GoalText可能很长,而且总是不同的
以下是我希望新的Select的外观
PlanID Recreation Community Part Employment
10133 Johnny is good at.. Johnny is currently going... Johnny is currently employeed at...
10144 Sammy is good at.. Sammy is currently going... Sammy is currently employed at...
对不起,所有的破折号。。。我尝试了4到5种不同的方式来显示这些表格,这就是我能解决的所有问题。我不得不用破折号作为空格来排列它
有什么想法吗?
Pivot
函数总是需要一个agreegate函数才能工作。因此,由于不能使用SUM
或AVG
,因此可以使用MIN
或MAX
因此,这里有一段代码可以得到您想要的
SELECT PlanId, [Recreation], [Community party], [Employment]
FROM
(SELECT PlanId, AreaDescription, GoalText
FROM dbo.TempArea) p
PIVOT
(
MAX (GoalText)
FOR AreaDescription IN
( [Recreation], [Community party], [Employment] )
) AS pvt
ORDER BY PlanId
正如在另一个答案中所述,您可以使用枢轴。但如果您没有已知数量的记录要转换,则可以使用动态透视 看
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.areadescription)
FROM t c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT planid, ' + @cols + ' from
(
select planid, areadescription, goaltext
from t
) x
pivot
(
min(goaltext)
for areadescription in (' + @cols + ')
) p '
execute(@query)