要得到这样的数据 SQL怎么写?

net_08 2011-07-21 02:24:35

一个表数据如下:
ID Price
1 30
2 49
4 12
.....

想得到如果下数据:


1 2 3 4
30 49 NULL 12

如果没数据自动填充NULL值的行转列怎么写,应该要写成动态吧。


...全文
50 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
--小F-- 2011-07-21
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 happyflystone 的回复:]
改改:

SQL code

declare @s varchar(8000)

select @s=isnull(@s+',','')+'['+cast([id] as varchar)+']=max(case when id='+cast([id] as varchar)+' then Price else NULL end)'
from(select number as id ……
[/Quote]
++
-狙击手- 2011-07-21
  • 打赏
  • 举报
回复
改改:
declare @s varchar(8000)

select @s=isnull(@s+',','')+'['+cast([id] as varchar)+']=max(case when id='+cast([id] as varchar)+' then Price else NULL end)'
from(select number as id from master..spt_values where type = 'P' and number >0 and number <=(select max(id) from ta))a
exec('select '+ @s+' from ta ')
go
GoAwayZ 2011-07-21
  • 打赏
  • 举报
回复
create table tb(id int,price int)
insert into tb
select 1,10 union select 2,20 union
select 3,70 union select 9,30 union
select 5,60 union select 8,40


declare @sql varchar(8000),@max int,@min int
select @max=MAX(id),@min=MIN(id) from tb
set @sql = ''
select @sql = @sql + ',max(case id when ' + rtrim(number) + ' then price end) [' + rtrim(number) + ']'
from master..spt_values where number between @min and @max and type='p'
set @sql = 'select '+stuff(@sql,1,1,'') + ' from tb '
exec(@sql)

/*
1 2 3 4 5 6 7 8 9
----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
10 20 70 NULL 60 NULL NULL 40 30
警告: 聚合或其他 SET 操作消除了 Null 值。

(1 行受影响)
cd731107 2011-07-21
  • 打赏
  • 举报
回复
先利用master..spt_values表左连上面的表得到一个连续的记录集,
再行转列
-狙击手- 2011-07-21
  • 打赏
  • 举报
回复
行列转换的例子,在精华里多的是

22,301

社区成员

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

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