sql server 语句报错, 各位大神来看看,,
[最优解释]
试试
DECLARE @s NVARCHAR(4000)
SET @s = ''
SELECT @s = @s + ',' + QUOTENAME([sid]) + '=max(case when [sid]='
+ QUOTENAME([sid], '''') + ' then [result] else 0.0 end)'
FROM tb
GROUP BY [sid]
SELECT @s = SUBSTRING(@s, 2, LEN(@s))
EXEC('select '+@s+' from tb ')
[其他解释]
declare @table table
(
id int,
sid nvarchar(5),
result nvarchar(10)
)
insert into @table(id,sid,result)
select 1 ,'001' ,'80.0' union all
select 2 ,'001' ,'90.0' union all
select 3 ,'001' ,'80.0' union all
select 4 ,'002' ,'56.0' union all
select 5 ,'002' ,'69.0' union all
select 6 ,'002' ,'89.0'
select sid=sid+' '+(select result+' ' from @table where sid=tab.sid for xml path(''))
from
(
select sid from @table group by sid
)tab
[其他解释]
只有一列了,他要的最少要把sid单独一列,result一列。这是你脚本的结果:
declare @table table
(
id int,
sid nvarchar(5),
result nvarchar(10)
)
insert into @table(id,sid,result)
select 1 ,'001' ,'80.0' union all
select 2 ,'001' ,'90.0' union all
select 3 ,'001' ,'80.0' union all
select 4 ,'002' ,'56.0' union all
select 5 ,'002' ,'69.0' union all
select 6 ,'002' ,'89.0'
select sid=sid+' '+(select result+' ' from @table where sid=tab.sid for xml path(''))
from
(
select sid from @table group by sid
)tab
/*
sid
----------------------------------------------------------------------------------------------------------------
001 80.0 90.0 80.0
002 56.0 69.0 89.0
*/
------其他解决方案--------------------
select sid,([1]+' '+[2]+' '+[3]) from (select sid,result,ROW_NUMBER() over(partition by sid order by sid )as bj from sss) as tt pivot(max(result) for bj in([1],[2],[3]))as t
00180.0 90.0 80.0
00256.0 69.0 89.0
这个就是两列了
[其他解释]
代码贴出来,别发图
[其他解释]
为表达式或者聚合函数指定的列别名,不能用于其他表达式运算,case...也算表达式的哦
[其他解释]
同一句select 中,所有操作都是“同时执行”,不存在先算左边再算右边的,所以你then num那里不能使用num,而要使用原有的计算公式
[其他解释]
表里面没有num列。
[其他解释]
declare @sql varchar(8000)
set @sql = 'select count(ADDRESS) as ' + 'num'
select @sql = @sql + ' , count(case ADDRESS when ''' + ADDRESS
+ ''' then num else null end) [' + ADDRESS + ']'
from (select distinct ADDRESS from T_CUSTOMER_ADDRESS) as a
set @sql = @sql + ' from T_CUSTOMER_ADDRESS group by ADDRESS'
exec(@sql)
[其他解释]
看代码, 我自己都看的有点头晕啦,,, 其实我要做的就是列转行(数目比较多,不能要case ),, 大神们来了, 真是激动呀,, 能否给个简单的列转行的例子。。我是新手, 太复杂的看不懂
[其他解释]
把数据都贴上来吧
[其他解释]
跟数据有关系么
[其他解释]
他叫你贴上去,直接帮你写好》。。。。
[其他解释]
噢 , 那大神们帮我把这个写出来吧 , 跟我要做的一样,
就是列转行(我要做的表数目比较多,不过我需要的只有两列sid,result,,不能要用case, )
示例表:a
id sid result
1 001 80.0
2 001 90.0
3 001 80.0
4 002 56.0
5 002 69.0
6 002 89.0
得出结果
sid
001 80.0 90.0 80.0
002 56.0 69.0 89.0
应该这么写SQL呢
[其他解释]
sql-server高手看看吧
[其他解释]
你这结果有问题吧
[其他解释]
什么问题?
[其他解释]
楼主要的结果就一列
[其他解释]
select * from (select sid,result,ROW_NUMBER() over(partition by sid order by sid )as bj from sss) as tt pivot(max(result) for bj in([1],[2],[3]))as t
00180.090.080.0
00256.069.089.0
[其他解释]
谢谢大神,, 不过还是不行
消息 8115,级别 16,状态 8,第 1 行
将 nvarchar 转换为数据类型 numeric 时出现算术溢出错误。
[其他解释]
19楼的不错,不过只能处理3个,不够动态,要是多的话就写死了。我那个可能是数据类型问题而已。你改一下吧
[其他解释]
嗯, 我想要的结果就是你说的, 不过我前面自己没写清楚吧, 谢谢两位啦,
[其他解释]
谢谢各位啦,, 结贴!!
[其他解释]
嗯,, 我要的就是能动态的,,,
[其他解释]
null