求一条统计sql语句(请高手赐教)

bjarner 2010-09-30 09:32:49

table1(itmid,projid,M_GCMC,addtime,projectstatus)
1 proj001 顶峰公园一栋 2009-01-01 0000100010....
2 proj002 侏罗世界二期 2009-02-02 0000100000....
3 proj003 杨家社区B-13 2009-03-03 0000100000....
--projectstatus代表状态位(100长度)每一位代表的项目名称根据table3来确定
table2(itmid,projid,m_gcmc,addtime,otherinfo) --存在多个表
--表名不固定,根据table3中的code来确定表名
设table2的名称为ZTYS_ITM 数据如下:
1 proj002 侏罗世界二期 2009-10-01 已经主体验收
2 proj001 顶峰公园一栋 2009-09-02 主体验收
2 proj003 杨家社区B-13 2009-09-10 主体验收
设table2的名称为JNYS_ITM 数据如下:
1 proj001 顶峰公园一栋 2010-02-02 节能验收完成

table3(code,stateindex,description)
ZTYS 5 主体验收
JNYS 9 节能验收
--stateindex 代表table2中添加记录时将table1相应工程的projectstatus的stateindex位置为1
--table2中的projid必需在table1中存在的

要得到的信息结构如下:
序号 工程编号 工程名称 主体验收 节能验收
1 proj001 顶峰公园一栋 2009-09-02 2010-02-02
2 proj002 侏罗世界二期 2009-10-01 ----
3 proj003 杨家社区B-13 2009-09-10 ----
...全文
117 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
bjarner 2010-09-30
  • 打赏
  • 举报
回复
试试看
coleling 2010-09-30
  • 打赏
  • 举报
回复
试着写了一个,看看是不是你想要的:

create proc sptest
as
begin
declare @strselect varchar(4000) --select部分
declare @strfrom varchar(4000) --from部分
select
@strselect = 'select a.itmid as ''序号'',a.projid as ''工程编号'',a.m_gcmc as ''工程名称''',
@strfrom = 'from table1 a '

declare @code varchar(50), @stateindex int, @description varchar(50)
declare @i int
select @i = 1

declare curtb3 cursor for
select code,stateindex,description from table3
open curtb3
fetch next from curtb3 into @code, @stateindex, @description
while @@fetch_status = 0
begin
select @strselect = @strselect + ', isnull(convert(varchar(10),b' + cast(@i as varchar(2)) + '.addtime,120),''----'') as ' + @description + ' '
select @strfrom = @strfrom + ' left join ' + @code + '_itm b' + cast(@i as varchar(2)) + ' on a.projid = b' + cast(@i as varchar(2)) + '.projid '
select @i = @i + 1

fetch next from curtb3 into @code, @stateindex, @description
end
close curtb3
deallocate curtb3

exec(@strselect+@strfrom)
end

exec sptest


序号 工程编号 工程名称 主体验收 节能验收
----------- -------- -------------------------------------------------- ---------- ----------
1 proj001 顶峰公园一栋 2009-09-02 2010-02-02
2 proj002 侏罗世界二期 2009-10-01 ----
3 proj003 杨家社区B-13 2009-09-10 ----

(3 行受影响)

22,300

社区成员

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

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