请用一个sql语句得出结果
从table1,table2中取出如table3所列格式数据 ,月份sql语句里不能写死,mysql数据库比如这样的sql是不对的,不能一个个比对月份,假设月份有1000个月,请问这样sql怎么写,非常感谢!!!select a.dep,
sum(case when b.mon=1 then b.yj else 0 end) as '一月份',
sum(case when b.mon=2 then b.yj else 0 end) as '二月份',
sum(case when b.mon=3 then b.yj else 0 end) as '三月份',
sum(case when b.mon=4 then b.yj else 0 end) as '四月份',
sum(case when b.mon=5 then b.yj else 0 end) as '五月份',
sum(case when b.mon=6 then b.yj else 0 end) as '六月份',
sum(case when b.mon=7 then b.yj else 0 end) as '七月份',
sum(case when b.mon=8 then b.yj else 0 end) as '八月份',
sum(case when b.mon=9 then b.yj else 0 end) as '九月份',
sum(case when b.mon=10 then b.yj else 0 end) as '十月份',
sum(case when b.mon=11 then b.yj else 0 end) as '十一月份',
sum(case when b.mon=12 then b.yj else 0 end) as '十二月份',
from table2 a left join table1 b on a.dep=b.dep这样也是不对的
select a.部门名称dname,b.业绩yj as '一月份',c.业绩yj as '二月份',d.业绩yj as '三月份'
from table1 a,table2 b,table2 c,table2 d
where a.部门dep = b.部门dep and b.月份mon = '一月份' and
a.部门dep = c.部门dep and c.月份mon = '二月份' and
a.部门dep = d.部门dep and d.月份mon = '三月份' and
---------------------------------------------------------------------------------
月份mon 部门dep 业绩yj
-------------------------------
一月份 01 10
一月份 02 10
一月份 03 5
二月份 02 8
二月份 04 9
三月份 03 8table2部门dep 部门名称dname
--------------------------------
  01 国内业务一部
  02 国内业务二部
  03 国内业务三部
  04 国际业务部table3 (result)部门dep 一月份 二月份 三月份
--------------------------------------
  01 10 null null
  02 10 8 null
  03 null 5 8
  04 null null 9------------------------------------------

解决方案 »

  1.   

    mysql数据库 呀建议去mysql 版问问
      

  2.   

    比如这样的sql是不对的,不能一个个比对月份,假设月份有1000个月:
    有跨年的?1年12个月你这是交叉表查询,你的SQL语句是静态的,动态的用SP累加生成字符串,动态执行SQL语句
      

  3.   

    你需要使用动态的SQL语句,无法仅用标准的SQL语句实现。另外一年只有12个月,哪来的1000个月?
      

  4.   


       建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
       参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
       
       1. 你的 create table xxx .. 语句
       2. 你的 insert into xxx ... 语句
       3. 结果是什么样,(并给以简单的算法描述)
       4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
       
       这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。