如何實現數據的交叉交換

dongfang2003 2004-08-23 09:34:13
有一個表T1
項次 站別 數量
1 A1 3
1 B1 2
2 B1 5
3 C1 6
4 D1 4
5 A1 7
如何用存儲過程實現得到如下結果
項次 A1 B1 C1 D1
1 3 2
2 5
3 6
4 4
5 7
注意:在結果中A1,B1,C1,D1和項次一樣都是字段名
...全文
130 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
qgbin 2004-08-30
  • 打赏
  • 举报
回复
在VB里好实现。
不过用存储过程没试过。
1.select distinct 项次 from (select 項次,站別,sum(數量) as 数量
from ...
group by 項次,站別 ) group by 項次
2.select distinct 站別 from (select 項次,站別,sum(數量) as 数量
from ...
group by 項次,站別 ) group by 站別
3.select 項次,站別,sum(數量) as 数量
from ...
group by 項次,站別
然后再判断项次,站别,依次写出来就可以了。
lihonggen0 2004-08-27
  • 打赏
  • 举报
回复
你可以参考:
http://dev.csdn.net/develop/article/18/18622.shtm
sangshuyezi 2004-08-27
  • 打赏
  • 举报
回复
那些sql语句都是在查询器中运行的,如果你是直接放在你写的存储过程中那需要根据你的数据库实际环境修改一下啦。
sangshuyezi 2004-08-27
  • 打赏
  • 举报
回复
我是运行成功了才写上来的。
你把错误提示贴上来吧。
dongfang2003 2004-08-27
  • 打赏
  • 举报
回复
運行了,不行,你調試一下,再把正確的寫下來
sangshuyezi 2004-08-26
  • 打赏
  • 举报
回复
Select * into tmpABC from (Select 1 as 项次,N'A1' as 站别, 3 as 数量
union select 1,N'B1',2
union select 2,N'B1',5
union select 3,N'C1',6
union select 4,N'D1',4
union select 5,N'A1',7) a

select * from tmpABC

declare @StrCol2 nvarchar(1000)
declare @StrSql nvarchar(1000)
declare @Col2 nvarchar(10)
set @StrCol2=''
set @StrSql=''
declare cursor_out cursor local for Select distinct 站别 from tmpABC
open cursor_out
fetch next from cursor_out into @Col2
while @@fetch_status=0
begin
set @StrCol2=@StrCol2 + ' , (case when 站别= ''' + @Col2 + ''' then 数量 else null end) as ' + @Col2
fetch next from cursor_out into @Col2
end
CLOSE cursor_out
DEALLOCATE cursor_out
set @StrSql='Select 项次' + @StrCol2 + ' from tmpABC'

exec(@StrSql)

drop table tmpABC
dongfang2003 2004-08-26
  • 打赏
  • 举报
回复
不會吧,高手都到哪裡去了
dongfang2003 2004-08-24
  • 打赏
  • 举报
回复
你想得也太簡單了,我忘記說了,站別是不確定的,可能是5個,也可能是10個,而且我要用存儲過程實現
dongfang2003 2004-08-24
  • 打赏
  • 举报
回复
你想得也太簡單了,我忘記說了,站別是不確定的,可能是5個,也可能是10個,而且我要用存儲過程實現
Andy__Huang 2004-08-23
  • 打赏
  • 举报
回复
select 項次,
A1=(case 站別 when A1 then 數量 else null end),
B1=(case 站別 when B1 then 數量 else null end),
C1=(case 站別 when C1 then 數量 else null end),
D1=(case 站別 when D1 then 數量 else null end)
FROM 表T1

1,216

社区成员

发帖
与我相关
我的任务
社区描述
VB 数据库(包含打印,安装,报表)
社区管理员
  • 数据库(包含打印,安装,报表)社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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