使用字符串列旋转 SQL 表的语法错误
Posted
技术标签:
【中文标题】使用字符串列旋转 SQL 表的语法错误【英文标题】:Syntax Error pivoting a SQL table using string columns 【发布时间】:2020-12-09 20:01:52 【问题描述】:我有一张职业这样的桌子:
Name | Occupation
-----------------
Sam | Doctor
Joe | Professor
John | Actor
Hailey | Singer
April | Doctor
我的目标是利用 PIVOT 函数将每个不同的职业显示为自己的列,如下所示:
Doctor | Professor | Singer | Actor
-----------------------------------
Sam | Joe | Hailey | John
April
我经历了各种类似问题的堆栈溢出问题,甚至利用了这里的文档并一步一步地跟进。我的努力是徒劳的,那又是什么呢?每次运行此代码时,我都会收到语法错误。有什么建议吗?
代码:
SELECT *
FROM(SELECT Name, Occupation from Occupations) as src
PIVOT
(MAX(Name) FOR Name IN [Doctor], [Professor], [Singer], [Actor]) as piv;
我在 Hackerrank 上解决这个问题,编译器是 mysql。我将其更改为 MSSQL,并且不再收到语法错误。
【问题讨论】:
【参考方案1】:您在 PIVOT 部分的每一侧都缺少 2 () 一个,我将添加的括号加粗:
([医生]、[教授]、[歌手]、[演员])——这2个
SELECT *
FROM (
SELECT Name, Occupation
FROM Occupations
) as src
PIVOT
(
MAX(Name) FOR Name IN ([Doctor], [Professor], [Singer], [Actor])
) as piv;
【讨论】:
我注意到这个愚蠢的错误,我的错。虽然,我在修复它时仍然收到语法错误。【参考方案2】:此查询将根据您的需要生成答案。上述答案并未按照您的要求提供答案。试试这个答案。
DECLARE @sql NVARCHAR(MAX) = N''
DECLARE @cols NVARCHAR(MAX) = N''
--Making the column list dynamically
SELECT @cols = STUFF((SELECT DISTINCT ', '+QUOTENAME( [T2].[Occupation])
FROM Occupation_data [T2]
FOR XML PATH('')), 1, 1, '')
--preparing PIVOT query dynamically.
SET @SQL = ' SELECT
*
into #temp
FROM
(
SELECT row_number() over (order by name) as id, [Name], [Occupation]
FROM Occupation_data
) AS cp
PIVOT
(
min([Name]) FOR [Occupation] IN (' + @cols + ')
) AS up;
Select
row_number() over (order by doctor asc ) as id1
,*
into #temp_1
from #temp where Doctor is not null
Select
row_number() over (Order by Actor asc ) as id2
,*
into #temp_2
from #temp where Actor is not null
Select
row_number() over (Order by Professor asc ) as id3
,*
into #temp_3
from #temp where Professor is not null
Select
row_number() over (Order by Singer asc ) as id4
,*
into #temp_4
from #temp where Singer is not null
select
A.Doctor
,B.Actor
,C.Professor
,D.Singer
from
#temp_1 A inner join
#temp_2 B ON A.id1 = B.id2
INNER JOIN
#temp_3 C ON A.id1 = C.id3
INNER JOIN
#temp_4 D ON A.id1 = d.id4
drop table #temp
drop table #temp_1
drop table #temp_2
drop table #temp_3
drop table #temp_4
';
PRINT( @SQL)
EXEC (@SQL)
输出:
如果这个答案对你有用,我会让它更通用并给你,这样你就可以将它应用于任何类似的工作。
【讨论】:
@nick_rinaldi 检查这个答案,让我知道。以上是关于使用字符串列旋转 SQL 表的语法错误的主要内容,如果未能解决你的问题,请参考以下文章