我尝试过实施 下面的SQL代码(SQL Server 2008),但在尝试使用我之前的帖子中的类似代码对表进行PIVOT时仍然遇到语法问题 how to create temp table while Joining multiple tables that have to be PIVOT 我现在很难过,需要紧急修理。
http://sqlfiddle.com/#!3/100bd/4
','附近的语法不正确:DECLARE @query AS NVARCHAR(MAX),@ colsPivot为NVARCHAR(MAX)选择@colsPivot = STUFF((SELECT','+ quotename('MEM'+ cast(MEMPER_Instance as varchar) (10))来自MEM_TEMP的+''+ REPLACE(c.name,'MEMPER ',''))交叉应用sys.columns为C,其中C.object_id = object_id('MEM_TEMP')和C.name不在('MEMPER_Instance','AHS_ID')组中由t.MEMPER_Instance,c.name顺序由t.MEMPER_Instance为XML路径(''),TYPE).value('。','NVARCHAR(MAX) )'),1,1,'')将@query ='SELECT *设置为#temp from(select ahs_id,''MEM''+ cast(MEMPER_instance as varchar(10))+''_''+ col col ,值来自(select ahs_id,MEMPER_Instance,cast(MEMPER_MinValue as float)MinValue,cast(MEMPER_MaxValue as float))MaxValue,cast(MEMPER_AvgValue as float)AvgValue,cast(MEMPER_MedianValue as float)MedianValue,cast(MEMPER_Count as float )来自MEM_TEMP的计数)x unpivot(col in的值(MinValue,MaxValue,AvgValue,MedianValue,Count))u)x1 pivot(col的max(value)) in('+ @colspivot +'))p; select * from #temp'exec(@query)
如果有人能帮助我找出问题,我将不胜感激。 感谢。
答案 0 :(得分:1)
你的一个select语句中连续有两个逗号
select ahs_id,
MEMPER_Instance,
,cast (MEMPER_MinValue as float) MinValue
首次投射前的额外逗号,投射中的2 as as float
和投射后的))
select ahs_id,
MEMPER_Instance,
,cast (MEMPER_MinValue as float) MinValue
,cast (MEMPER_MaxValue as as float)) MaxValue
,cast (MEMPER_AvgValue as float) AvgValue
,cast (MEMPER_MedianValue as float) MedianValue
,cast (MEMPER_Count as as float) Count
解决这4个错误并且它在小提琴上运行
答案 1 :(得分:1)
您的脚本有几处错误。
MEMPER_Instance,
as
次转化float
次
脚本应为:
select * from MEM_TEMP;
DECLARE @query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT ','
+ quotename('MEM'+ cast(MEMPER_Instance as varchar(10))+'_'+REPLACE(c.name, 'MEMPER_', ''))
from MEM_TEMP t cross apply sys.columns as C
where C.object_id = object_id('MEM_TEMP')
and C.name not in ('MEMPER_Instance','AHS_ID')
group by t.MEMPER_Instance, c.name
order by t.MEMPER_Instance
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= ' SELECT * into ##temp
from
(
select ahs_id,
''MEM''+cast(MEMPER_instance as varchar(10))+''_''+col col,
value
from
(
select ahs_id,
MEMPER_Instance
,cast (MEMPER_MinValue as float) MinValue
,cast (MEMPER_MaxValue as float) MaxValue
,cast (MEMPER_AvgValue as float) AvgValue
,cast (MEMPER_MedianValue as float) MedianValue
,cast (MEMPER_Count as float) Count
from MEM_TEMP
) x
unpivot
(
value
for col in (
MinValue,
MaxValue,
AvgValue,
MedianValue,
Count
)
) u
) x1
pivot
(
max(value)
for col in ('+ @colspivot +')
) p ; '
exec(@query)
select *
from ##temp