求sql语句。高手帮下忙。

迷惘2013 2013-09-03 10:27:02
现在数据表是这样的:
单位代码——管护方式——相关林班号——面积
120101——2——2——1
120102 ——1 ——1,3——2
120103—— 3——1,2,4——3
120102——1——2,3——4
120102—— 2 ——1,4——5
想要的查询结果是
林业局——林场——方式1林班个数——方式1面积——方式2面积——方式3面积——方式2林班个数——方式3林班个数
01——01——0——null——1——null——X——x
01——02——1——6——5——null——X——x
01——03——0——null——null——3——X——x
其中,林业局为单位代码3,4位,林场为5,6位,林班个数为明细中林班号的个数。求sql语句。
...全文
134 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
--小F-- 2013-09-03
  • 打赏
  • 举报
回复
力气活啊 还需要拆分字符串 交给楼下了。
唐诗三百首 2013-09-03
  • 打赏
  • 举报
回复

create table u01
(单位代码 varchar(10), 管护方式 int, 相关林班号 varchar(10), 面积 int)
 
insert into u01
 select '120101', 2, '2', 1 union all
 select '120102', 1, '1,3', 2 union all
 select '120103', 3, '1,2,4', 3 union all
 select '120102', 1, '2,3', 4 union all
 select '120102', 2, '1,4', 5
 
 
declare @tsql varchar(6000)
 
select @tsql=isnull(@tsql+',','')+
       '(select count(1)
        from
        (select 相关林班号 from u01 b
         where substring(b.单位代码,3,2)=substring(a.单位代码,3,2)
         and substring(b.单位代码,5,2)=substring(a.单位代码,5,2)
         and b.管护方式='+rtrim(f)+') c
        inner join master.dbo.spt_values d
        on d.type=''P'' and d.number between 1 and len(c.相关林班号)
        and substring('',''+c.相关林班号,d.number,1)='','') ''方式'+rtrim(f)+'林班个数'',
       (select sum(面积) from u01 b
         where substring(b.单位代码,3,2)=substring(a.单位代码,3,2)
         and substring(b.单位代码,5,2)=substring(a.单位代码,5,2)
         and b.管护方式='+rtrim(f)+') ''方式'+rtrim(f)+'面积'' '
 from (select distinct 管护方式 'f' from u01) t

select @tsql='select substring(a.单位代码,3,2) ''林业局'',
              substring(a.单位代码,5,2) ''林场'','+@tsql
            +' from u01 a '
            +' group by substring(a.单位代码,3,2),substring(a.单位代码,5,2) '

exec(@tsql)

/*
林业局  林场  方式1林班个数   方式1面积   方式2林班个数   方式2面积   方式3林班个数   方式3面积
---- ---- ----------- ----------- ----------- ----------- ----------- -----------
01   01       0           NULL        1           1           0           NULL
01   02       4           6           2           5           0           NULL
01   03       0           NULL        0           NULL        3           3

(3 row(s) affected)
*/
yangbo4235 2013-09-03
  • 打赏
  • 举报
回复
select
substring(a.单位代码,2,2),
substring(a.单位代码,4,2),
(select count(*) from 表 b where b.单位代码=a.单位代码 and b.方式=1 ) as 方式1林班个数,
(select sum(面积) from 表 b where b.单位代码=a.单位代码 and b.方式=1 ) as 方式1面积,
(select sum(面积) from 表 b where b.单位代码=a.单位代码 and b.方式=2 ) as 方式2面积,
(select sum(面积) from 表 b where b.单位代码=a.单位代码 and b.方式=3 ) as 方式3面积,
(select count(*) from 表 b where b.单位代码=a.单位代码 and b.方式=2 ) as 方式2林班个数,
(select count(*) from 表 b where b.单位代码=a.单位代码 and b.方式=3 ) as 方式3林班个数
from 表 a
where a.单位代码 like '1201%'
group a.单位代码

22,301

社区成员

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

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