请教SQL语句

GSDN 2003-08-20 10:32:46
有原始数据如下:
ID ProductName UnitPrice
1 ProductName1 1000
1 ProductName1 2000
1 ProductName1 3000
...

现需将以上数据输出成如下格式:
ID ProductName UnitPrice1 UnitPrice2 UnitPrice3...
1 ProductName1 1000 2000 3000

请教实现此转换的SQL语句。
...全文
37 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2003-08-20
  • 打赏
  • 举报
回复
典型交叉表

如果ProductName记录条数不固定,用动态生成SQL的方法:

ID ProductName UnitPrice
declare @sql varchar(8000),@i int,@ich varchar(20)
select @sql=''
,@i=max(cc),@ich=cast(@i as varchar),@i=@i-1
while @i>=0
select @sql=',UnitPrice'+cast(@i+1 as varchar)+'=max(case myid%'+@ich+' when '+cast(@i as varchar)+' then UnitPrice end)'+@sql,@i=@i-1
set @sql='select ID,ProductName'+@sql+' from #tb gruop by ID,ProductName'
select myid=identity(int,1,1),* into #tb from 原始表
exec(@sql)
drop table #tb
CrazyFor 2003-08-20
  • 打赏
  • 举报
回复
select identity(int,1,1)xh,cast(id as int) id,productname,unitprice into #t from 表
select ID,ProductName
,sum(case when (xh-1)%3=0 then unitprice end ) unitprice1
,sum(case when (xh-1)%3=1 then unitprice end ) unitprice2
,sum(case when (xh-1)%3=2 then unitprice end ) unitprice3
from #t group by ID,ProductName

针对每个产品三种价格的情况.
amtyuranus 2003-08-20
  • 打赏
  • 举报
回复
写一个存储过程来实现

一条sql语句可能很难,但可以的,假如你记录数不是固定的,那写一个函数就可以了
GSDN 2003-08-20
  • 打赏
  • 举报
回复
Thanks.

22,206

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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