求如下问题的sql语句

ahead_lin 2004-09-30 11:13:21
1 如何把一个字段的字符串连起来? 不能用游标
比如
ID Content
1 'boy'
2 'girl'
3 'cat'
想得到结果 'boygirlcat'

3
有一表
Month line Amont
1 'A' 100
1 'A' 300
1 'c' 100
2 'd' 200
2 'A' 200
如何得到结果
Month line Amount percentage1 percentage2
1 'A' 400 0.8 0.4
1 'c' 300 0.2 0.1
2 'A' 200 0.5 0.25
2 'd' 200 0.5 0.25
Amount容易得到,但percentage1 和 percentage2如何在不能用临时表的情况下完成?
...全文
113 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
szh3210 2004-10-01
  • 打赏
  • 举报
回复
create table test (id int IDENTITY(1,1)PRIMARY KEY ,Content
varchar(20))




insert test select 'boy'
union all
select 'girl'
union all
select 'cat'

declare @str as varchar(800)
select @str=isnull(@str,'')+Content from test
select @str


(所影响的行数为 3 行)


----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
boygirlcat

(所影响的行数为 1 行)
General521 2004-10-01
  • 打赏
  • 举报
回复
针对第一个问题:
declare @str varchar(8000)
set @str=''
select @str=@str+[content] from table
print replace(@str,' ','') --用replace函数将字符串中间的空格全部清除.


针对第二个问题:没看懂.
ilons1 2004-10-01
  • 打赏
  • 举报
回复
对1有个简单的办法,写个函数:
declare @str
set @str = ''
select @str = @str + [列名] from 表名 where ....
,然后在SP中引用就好啦,我就是这么搞的至于传入参数,自己看需要办法

3点 : 不知道理解了你的意思没有 ,但这样对大数据量来说速度并不很好
select a.month , a.line ,a.amont , a.amont / b.mtotal , a.mont/(b.mtotal*2)
from
(select month , line , amont = sum (amont) form T1 group by month , line) a left join
(select month , mTotal = sum(amont) from T1 group by month) b on a.month = b.month
yjdn 2004-10-01
  • 打赏
  • 举报
回复
1:declare @a varchar(100)
set @a=''
select @a=@a+Content from tb
print @a

--一般把上面语句变为函数

2:
select month,line,Amont,
percentage1=cast(cast(Amont as numeric(8,2))/percentage as numeric(8,2)),
percentage2=cast(cast(Amont as numeric(8,2))/(2*percentage) as numeric(8,2))
from
(select [month],line ,Amont=sum(Amont) ,
percentage=(select sum(Amont) from tb where month=a.month)

from tb a group by [month],line )b

--结果:
1 A 400 .80 .40
1 c 100 .20 .10
2 A 200 .50 .25
2 d 200 .50 .25


--质疑:楼主这一列1 'c' 300 0.2 0.1中Amont应该是100吧?
--2:不知道楼主的percentage2是怎么算的,估且用percentage1/2来算
YnewnewY 2004-09-30
  • 打赏
  • 举报
回复
3.
SELECT ..... FROM ...... GROUP BY Month, line
黑马 2004-09-30
  • 打赏
  • 举报
回复
1、得用游标,好像没有专门的函数连接字符串

3、percentage2=percentage1/2吗?

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧