RT:
图一:
+--------+------+------+
| mon    | dep  | yj   |
+--------+------+------+
| 一月份 |    1 |   10 |
| 一月份 |    2 |   10 |
| 一月份 |    3 |    5 |
| 二月份 |    2 |    8 |
| 二月份 |    4 |    9 |
| 三月份 |    3 |    8 |
+--------+------+------+
图二:
+------+--------+
| dep  | dname  |
+------+--------+
|    1 | 一部   |
|    2 | 二部   |
|    3 | 三部   |
|    4 | 国际部 |
+------+--------+要达到以下的效果,如何写sql语句,如果能稍微解释下sql语句的每部分就更好了。
  dep       dname       一月份      二月份    三月份
--------------------------------------
   01     国内业务一部   10          null      null
   02     国内业务二部   10           8        null
   03     国内业务三部   null         5         8
   04     国际业务部     null        null       9

解决方案 »

  1.   

    http://blog.csdn.net/acmain_chm/article/details/4283943
    MySQL交叉表
      

  2.   

    其中的一种方法。
      select a.dep,a.dname,
    sum(if(mon='一月份',yj,0)) as `一月份`,
    sum(if(mon='二月份',yj,0)) as `二月份`,
    sum(if(mon='三月份',yj,0)) as `三月份`
      from 图二 a left join 图一 b on a.dep=b.dep
      group by a.dep,a.dname
      

  3.   

    select B.dep,B.dname
    ,sum(case when A.mon ='一月' then yj end) as 一月份
    ,sum(case when A.mon ='二月' then yj end) as 二月份
    ,sum(case when A.mon ='三月' then yj end) as 三月份
    from tb1 A,tb2 B
    where A.dep = B.dep
    group by B.dep,B.dname
      

  4.   

    select distinct a.dep,b.dname
    ,(select yj from yjtbl where dep=a.dep and mon='一月份') as 一月份
    ,(select yj from yjtbl where dep=a.dep and mon='二月份') as 二月份
    ,(select yj from yjtbl where dep=a.dep and mon='三月份') as 三月份
    from yjtbl as a inner join deptbl as b on a.dep=b.dep;
    每个月份写一个子查询,每行的每个子查询只返回一个值,值为符合条件的业绩值或者null,然后和部门表联接。此时的结果集行数和业绩表相同,需要用DISTINCT来去掉重复行。
      

  5.   

    写完试完语句,回复之后才看到二楼三楼的回复,果然精炼~
    LZ千万不要用我写的这个,不但要用N多个低效的相关子查询,而且还要假设业绩表(mon,dep)是唯一的,否则结果都是错误的
    向二楼三楼致敬,学习了~
    另外,提醒楼主,二楼的答案里,不存在的业绩为0,三楼的为null~
      

  6.   

    2L,3L 能不能说一下你们写这种sql的思维方式,就是每一步是如何想的。这种小东东对你们来说肯定都小菜了,麻烦解释下哈。谢谢了。还有 最后那个group by 为什么要是group by dep ,dname。在这里我试了下,group by dep 也行,但我昨天做别的数据的时候有时候又不行。
      

  7.   

    group by dep ,dname:标准的SQL语法
    SUM(IF()) OR SUM(CASE WHEN):交叉表查询
      

  8.   

    汗 ,大神说话都很简洁啊。7L大神,如果表2不止这两个字段,那group by后面都要跟着吗?
      

  9.   

    谢谢大家,我现在基本上了解这种sql 的思维方式了。唉,还是基础太差了,几年没碰过数据库,这种sql写起来关键是要了解sql的执行顺序唉,这种数据库最基础的东西我都忘了。